Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
MarcT512 authored May 15, 2024
1 parent 0a979c5 commit b953ba3
Showing 1 changed file with 22 additions and 1 deletion.
23 changes: 22 additions & 1 deletion lib/misc.c
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,28 @@ void closefrom_shim(struct lsof_context *ctx, int low) {
if (MaxFd > low && syscall(SYS_close_range, low, MaxFd - 1, 0) == 0)
return;
# endif
/* slow fallback */
# if defined(LINUX_LSOF_H)
/* optimized fallback for Linux:
* iterate /proc/self/fd and close fd's that are not that directory itself
*/
long fd;
char *endp;
struct dirent *dent;
DIR *dirp;

dirp = opendir("/proc/self/fd");
if (dirp) {
while ((dent = readdir(dirp)) != NULL) {
fd = strtol(dent->d_name, &endp, 10);
if (dent->d_name != endp && *endp == '\0' && fd >= 0 &&
fd < INT_MAX && fd >= low && fd != dirfd(dirp))
(void)close((int)fd);
}
(void)closedir(dirp);
return;
}
# endif
/* slow brute force fallback */
for (i = low; i < MaxFd; i++)
(void)close(i);
#endif /* !defined(HAS_CLOSEFROM) */
Expand Down

0 comments on commit b953ba3

Please sign in to comment.