2 * Copyright (c) 2004-2005, 2007, 2010, 2012-2013
3 * Todd C. Miller <Todd.Miller@courtesan.com>
5 * Permission to use, copy, modify, and distribute this software for any
6 * purpose with or without fee is hereby granted, provided that the above
7 * copyright notice and this permission notice appear in all copies.
9 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 #ifndef HAVE_CLOSEFROM
22 #include <sys/types.h>
32 #endif /* STDC_HEADERS */
34 #ifdef HAVE_PSTAT_GETPROC
35 # include <sys/param.h>
36 # include <sys/pstat.h>
40 # define NAMLEN(dirent) strlen((dirent)->d_name)
42 # define dirent direct
43 # define NAMLEN(dirent) (dirent)->d_namlen
44 # ifdef HAVE_SYS_NDIR_H
45 # include <sys/ndir.h>
47 # ifdef HAVE_SYS_DIR_H
58 #ifndef HAVE_FCNTL_CLOSEM
60 # define closefrom_fallback closefrom
65 * Close all file descriptors greater than or equal to lowfd.
66 * This is the expensive (ballback) method.
69 closefrom_fallback(int lowfd)
74 * Fall back on sysconf() or getdtablesize(). We avoid checking
75 * resource limits since it is possible to open a file descriptor
76 * and then drop the rlimit such that it is below the open fd.
79 maxfd = sysconf(_SC_OPEN_MAX);
81 maxfd = getdtablesize();
82 #endif /* HAVE_SYSCONF */
86 for (fd = lowfd; fd < maxfd; fd++)
87 (void) close((int) fd);
91 * Close all file descriptors greater than or equal to lowfd.
92 * We try the fast way first, falling back on the slow method.
94 #if defined(HAVE_FCNTL_CLOSEM)
98 if (fcntl(lowfd, F_CLOSEM, 0) == -1)
99 closefrom_fallback(lowfd);
101 #elif defined(HAVE_PSTAT_GETPROC)
105 struct pst_status pstat;
108 if (pstat_getproc(&pstat, sizeof(pstat), 0, getpid()) != -1) {
109 for (fd = lowfd; fd <= pstat.pst_highestfd; fd++)
112 closefrom_fallback(lowfd);
115 #elif defined(HAVE_DIRFD)
124 /* Use /proc/self/fd directory if it exists. */
125 if ((dirp = opendir("/proc/self/fd")) != NULL) {
126 while ((dent = readdir(dirp)) != NULL) {
127 fd = strtol(dent->d_name, &endp, 10);
128 if (dent->d_name != endp && *endp == '\0' &&
129 fd >= 0 && fd < INT_MAX && fd >= lowfd && fd != dirfd(dirp))
130 (void) close((int) fd);
132 (void) closedir(dirp);
134 closefrom_fallback(lowfd);
136 #endif /* HAVE_FCNTL_CLOSEM */
137 #endif /* HAVE_CLOSEFROM */