]> git.decadent.org.uk Git - nfs-utils.git/blob - support/nfs/closeall.c
mount.nfs: Fix retry= to handle lack of reserved port situation
[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
11 void
12 closeall(int min)
13 {
14         DIR *dir = opendir("/proc/self/fd");
15         if (dir != NULL) {
16                 int dfd = dirfd(dir);
17                 struct dirent *d;
18
19                 while ((d = readdir(dir)) != NULL) {
20                         char *endp;
21                         long n = strtol(d->d_name, &endp, 10);
22                         if (*endp != '\0' && n >= min && n != dfd)
23                                 (void) close(n);
24                 }
25                 closedir(dir);
26         } else {
27                 int fd = sysconf(_SC_OPEN_MAX);
28                 while (--fd >= min)
29                         (void) close(fd);
30         }
31 }