Skip to content

Commit 4514e42

Browse files
committed
Try doing runtime close_range syscall
1 parent 8a2bf90 commit 4514e42

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
@@ -13,6 +13,7 @@
1313

1414
#include <unistd.h>
1515
#include <errno.h>
16+
#include <sys/syscall.h>
1617
#include <sys/wait.h>
1718

1819
#ifdef HAVE_FCNTL_H
@@ -23,23 +24,23 @@
2324
#include <signal.h>
2425
#endif
2526

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

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

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

0 commit comments

Comments
 (0)