Skip to content

Commit 9379a84

Browse files
committed
Try doing runtime close_range syscall
1 parent ccb5064 commit 9379a84

File tree

1 file changed

+15
-14
lines changed

1 file changed

+15
-14
lines changed

cbits/posix/runProcess.c

Lines changed: 15 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
#include <unistd.h>
1313
#include <errno.h>
14+
#include <sys/syscall.h>
1415
#include <sys/wait.h>
1516

1617
#ifdef HAVE_FCNTL_H
@@ -21,23 +22,23 @@
2122
#include <signal.h>
2223
#endif
2324

24-
#if defined(HAVE_LINUX_CLOSE_RANGE_H)
25-
#define _GNU_SOURCE
26-
#include <linux/close_range.h>
27-
#endif
28-
2925
void
3026
closefrom_excluding(int lowfd, int excludingFd) {
31-
#if defined(HAVE_CLOSE_RANGE)
32-
close_range(lowfd, excludingFd - 1);
33-
closefrom(excludingFd + 1);
34-
#else
35-
for (int i = lowfd; i < excludingFd; i++) {
36-
close(i);
37-
}
27+
// Try using the close_range syscall, provided in Linux kernel >= 5.9.
28+
// We do this directly because not all C libs provide a wrapper (like musl)
29+
long ret = syscall(SYS_close_range, lowfd, excludingFd - 1);
3830

39-
closefrom(excludingFd + 1);
40-
#endif
31+
if (ret != -1) {
32+
// If that worked, closefrom the remaining range
33+
closefrom(excludingFd + 1);
34+
} else {
35+
// Otherwise, fall back to a loop + closefrom
36+
for (int i = lowfd; i < excludingFd; i++) {
37+
close(i);
38+
}
39+
40+
closefrom(excludingFd + 1);
41+
}
4142
}
4243

4344
// If a process was terminated by a signal, the exit status we return

0 commit comments

Comments
 (0)