summaryrefslogtreecommitdiff
path: root/quickjs-libc.c
diff options
context:
space:
mode:
authorCharlie Gordon <github@chqrlie.org>2024-05-10 01:57:55 +0200
committerGitHub <noreply@github.com>2024-05-10 01:57:55 +0200
commitd378a9f3a583cb787c390456e27276d0ee377d23 (patch)
tree78a470642452d5f7ed4e0dfa01722a7ce15edf07 /quickjs-libc.c
parent97be5a32af9c942765250bbae30c7d792815e5e3 (diff)
downloadquickjs-d378a9f3a583cb787c390456e27276d0ee377d23.tar.gz
quickjs-d378a9f3a583cb787c390456e27276d0ee377d23.zip
Improve `js_os_exec` (#295)
- use $(shell) make command to test if closefrom() is available - use closefrom() if available in js_os_exec() - limit the fallback loop to 1024 handles to avoid costly loop on linux alpine. PR inspired by @nicolas-duteil-nova
Diffstat (limited to 'quickjs-libc.c')
-rw-r--r--quickjs-libc.c26
1 files changed, 22 insertions, 4 deletions
diff --git a/quickjs-libc.c b/quickjs-libc.c
index dd9f55f..8137150 100644
--- a/quickjs-libc.c
+++ b/quickjs-libc.c
@@ -3015,7 +3015,6 @@ static JSValue js_os_exec(JSContext *ctx, JSValueConst this_val,
}
if (pid == 0) {
/* child */
- int fd_max = sysconf(_SC_OPEN_MAX);
/* remap the stdin/stdout/stderr handles if necessary */
for(i = 0; i < 3; i++) {
@@ -3024,9 +3023,28 @@ static JSValue js_os_exec(JSContext *ctx, JSValueConst this_val,
_exit(127);
}
}
-
- for(i = 3; i < fd_max; i++)
- close(i);
+#if defined(HAVE_CLOSEFROM)
+ /* closefrom() is available on many recent unix systems:
+ Linux with glibc 2.34+, Solaris 9+, FreeBSD 7.3+,
+ NetBSD 3.0+, OpenBSD 3.5+.
+ Linux with the musl libc and macOS don't have it.
+ */
+
+ closefrom(3);
+#else
+ {
+ /* Close the file handles manually, limit to 1024 to avoid
+ costly loop on linux Alpine where sysconf(_SC_OPEN_MAX)
+ returns a huge value 1048576.
+ Patch inspired by nicolas-duteil-nova. See also:
+ https://stackoverflow.com/questions/73229353/
+ https://stackoverflow.com/questions/899038/#918469
+ */
+ int fd_max = min_int(sysconf(_SC_OPEN_MAX), 1024);
+ for(i = 3; i < fd_max; i++)
+ close(i);
+ }
+#endif
if (cwd) {
if (chdir(cwd) < 0)
_exit(127);