Skip to content

Commit

Permalink
Merge pull request #316 from MarcT512/master
Browse files Browse the repository at this point in the history
[linux] closefrom_shim: Add optimized fallback for platforms without closefrom or close_range
  • Loading branch information
jiegec authored Jun 2, 2024
2 parents cd5bb9b + b953ba3 commit fe15efa
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 fe15efa

Please sign in to comment.