Commit b564e7ca59

Andrew Kelley <andrew@ziglang.org>
2019-09-05 21:09:13
os: raise maximum file descriptor limit
Do a binary search for the maximum RLIMIT_NOFILE. Patch lifted from node.js commit 6820054d2d42ff9274ea0755bea59cfc4f26f353
1 parent 2045b4d
Changed files (1)
src
src/os.cpp
@@ -45,6 +45,7 @@ typedef SSIZE_T ssize_t;
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <sys/wait.h>
+#include <sys/resource.h>
 #include <fcntl.h>
 #include <limits.h>
 #include <spawn.h>
@@ -1374,6 +1375,29 @@ int os_init(void) {
 #elif defined(__MACH__)
     host_get_clock_service(mach_host_self(), SYSTEM_CLOCK, &macos_monotonic_clock);
     host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &macos_calendar_clock);
+#endif
+#if defined(ZIG_OS_POSIX)
+    // Raise the open file descriptor limit.
+    // Code lifted from node.js
+    struct rlimit lim;
+    if (getrlimit(RLIMIT_NOFILE, &lim) == 0 && lim.rlim_cur != lim.rlim_max) {
+        // Do a binary search for the limit.
+        rlim_t min = lim.rlim_cur;
+        rlim_t max = 1 << 20;
+        // But if there's a defined upper bound, don't search, just set it.
+        if (lim.rlim_max != RLIM_INFINITY) {
+            min = lim.rlim_max;
+            max = lim.rlim_max;
+        }
+        do {
+            lim.rlim_cur = min + (max - min) / 2;
+            if (setrlimit(RLIMIT_NOFILE, &lim)) {
+                max = lim.rlim_cur;
+            } else {
+                min = lim.rlim_cur;
+            }
+        } while (min + 1 < max);
+    }
 #endif
     return 0;
 }