Skip to content

Commit b953ba3

Browse files
authored
Add files via upload
Add an optimized fallback in closefrom_shim() for Linux, if the platform doesn't support closefrom or close_range. Iterate /proc/self/fd and close anything which is not that directory itself.
1 parent 0a979c5 commit b953ba3

1 file changed

Lines changed: 22 additions & 1 deletion

File tree

lib/misc.c

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,28 @@ void closefrom_shim(struct lsof_context *ctx, int low) {
227227
if (MaxFd > low && syscall(SYS_close_range, low, MaxFd - 1, 0) == 0)
228228
return;
229229
# endif
230-
/* slow fallback */
230+
# if defined(LINUX_LSOF_H)
231+
/* optimized fallback for Linux:
232+
* iterate /proc/self/fd and close fd's that are not that directory itself
233+
*/
234+
long fd;
235+
char *endp;
236+
struct dirent *dent;
237+
DIR *dirp;
238+
239+
dirp = opendir("/proc/self/fd");
240+
if (dirp) {
241+
while ((dent = readdir(dirp)) != NULL) {
242+
fd = strtol(dent->d_name, &endp, 10);
243+
if (dent->d_name != endp && *endp == '\0' && fd >= 0 &&
244+
fd < INT_MAX && fd >= low && fd != dirfd(dirp))
245+
(void)close((int)fd);
246+
}
247+
(void)closedir(dirp);
248+
return;
249+
}
250+
# endif
251+
/* slow brute force fallback */
231252
for (i = low; i < MaxFd; i++)
232253
(void)close(i);
233254
#endif /* !defined(HAS_CLOSEFROM) */

0 commit comments

Comments
 (0)