]> git.decadent.org.uk Git - nfs-utils.git/blob - support/nfs/closeall.c
nfs-utils: Fix source code character encoding
[nfs-utils.git] / support / nfs / closeall.c
1 /*
2  * support/nfs/closeall.c
3  * Close all file descriptors greater than some limit,
4  * Use readdir "/proc/self/fd" to avoid excess close(2) calls.
5  */
6
7 #include <unistd.h>
8 #include <stdlib.h>
9 #include <dirent.h>
10 #include <errno.h>
11
12 void
13 closeall(int min)
14 {
15         char *endp;
16         long n;
17         DIR *dir = opendir("/proc/self/fd");
18
19         if (dir != NULL) {
20                 int dfd = dirfd(dir);
21                 struct dirent *d;
22
23                 while ((d = readdir(dir)) != NULL) {
24                         errno = 0;
25                         n = strtol(d->d_name, &endp, 10);
26                         if (!errno && *endp == '\0' && endp != d->d_name &&
27                             n >= min && n != dfd)
28                                 (void) close(n);
29                 }
30                 closedir(dir);
31         } else {
32                 int fd = sysconf(_SC_OPEN_MAX);
33                 while (--fd >= min)
34                         (void) close(fd);
35         }
36 }