From 6037f2cdcf73f546a16ffd6c8e9079ee5b16fbbc Mon Sep 17 00:00:00 2001 From: Nicolas Duteil Date: Sun, 17 Dec 2023 00:24:03 +0100 Subject: [PATCH] refactor: use /proc to compute fd_max on linux --- quickjs-libc.c | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/quickjs-libc.c b/quickjs-libc.c index e180dd0..ea02440 100644 --- a/quickjs-libc.c +++ b/quickjs-libc.c @@ -2968,6 +2968,36 @@ static JSValue js_os_exec(JSContext *ctx, JSValueConst this_val, } } +#if defined(__linux__) + int pid = getpid(); + int max_fd = 0; + char path[32]; + struct stat statbuf; + sprintf(path, "/proc/%d/fd", pid); + if (stat(path, &statbuf) == 0) { + if (S_ISDIR(statbuf.st_mode)) { + DIR *dir = opendir(path); + if (dir) { + struct dirent *subdir; + int fd; + for(;;) { + subdir = readdir(dir); + if (!subdir) { + break; + } + fd = atoi(subdir->d_name); + if (fd > max_fd) { + max_fd = fd; + } + } + if (max_fd > 0) { + fd_max = max_fd; + } + closedir(dir); + } + } + } +#endif for(i = 3; i < fd_max; i++) close(i); if (cwd) {