summaryrefslogtreecommitdiff
path: root/support/nfs/closeall.c
blob: e07253e2fa320401588db34ec9799251ad2fc801 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/*
 * support/nfs/closeall.c
 * Close all file descriptors greater than some limit,
 * Use readdir "/proc/self/fd" to avoid excess close(2) calls.
 */

#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>

#include "nfslib.h"

void
closeall(int min)
{
	char *endp;
	long n;
	DIR *dir = opendir("/proc/self/fd");

	if (dir != NULL) {
		int dfd = dirfd(dir);
		struct dirent *d;

		while ((d = readdir(dir)) != NULL) {
			errno = 0;
			n = strtol(d->d_name, &endp, 10);
			if (!errno && *endp == '\0' && endp != d->d_name &&
			    n >= min && n != dfd)
				(void) close(n);
		}
		closedir(dir);
	} else {
		int fd = sysconf(_SC_OPEN_MAX);
		while (--fd >= min)
			if(fd >= 0)
				(void) close(fd);
	}
}