From d25a8222651671613322677d17b2f987135e02cd Mon Sep 17 00:00:00 2001
From: sewn <sewn@disroot.org>
Date: Sat, 24 Aug 2024 19:26:26 +0300
Subject: [PATCH] set max open file descriptors to available max

---
 dwl.c | 22 ++++++++++++++++++++++
 1 file changed, 22 insertions(+)

diff --git a/dwl.c b/dwl.c
index a2711f6..163ebdd 100644
--- a/dwl.c
+++ b/dwl.c
@@ -8,6 +8,7 @@
 #include <signal.h>
 #include <stdio.h>
 #include <stdlib.h>
+#include <sys/resource.h>
 #include <sys/wait.h>
 #include <time.h>
 #include <unistd.h>
@@ -316,6 +317,7 @@ static void pointerfocus(Client *c, struct wlr_surface *surface,
 static void printstatus(void);
 static void powermgrsetmode(struct wl_listener *listener, void *data);
 static void quit(const Arg *arg);
+static void restorerlimit(void);
 static void rendermon(struct wl_listener *listener, void *data);
 static void requestdecorationmode(struct wl_listener *listener, void *data);
 static void requeststartdrag(struct wl_listener *listener, void *data);
@@ -358,6 +360,7 @@ static void zoom(const Arg *arg);
 
 /* variables */
 static const char broken[] = "broken";
+static struct rlimit og_rlimit;
 static pid_t child_pid = -1;
 static int locked;
 static void *exclusive_focus;
@@ -2096,6 +2099,15 @@ quit(const Arg *arg)
 	wl_display_terminate(dpy);
 }
 
+void
+restorerlimit(void)
+{
+	if (og_rlimit.rlim_cur == 0)
+		return;
+	if (setrlimit(RLIMIT_NOFILE, &og_rlimit) < 0)
+		die("setrlimit:");
+}
+
 void
 rendermon(struct wl_listener *listener, void *data)
 {
@@ -2232,6 +2244,7 @@ run(char *startup_cmd)
 		if ((child_pid = fork()) < 0)
 			die("startup: fork:");
 		if (child_pid == 0) {
+			restorerlimit();
 			setsid();
 			dup2(piperw[0], STDIN_FILENO);
 			close(piperw[0]);
@@ -2429,10 +2442,18 @@ setsel(struct wl_listener *listener, void *data)
 void
 setup(void)
 {
+	struct rlimit new_rlimit;
 	int i, sig[] = {SIGCHLD, SIGINT, SIGTERM, SIGPIPE};
 	struct sigaction sa = {.sa_flags = SA_RESTART, .sa_handler = handlesig};
 	sigemptyset(&sa.sa_mask);
 
+	if (getrlimit(RLIMIT_NOFILE, &og_rlimit) < 0)
+		die("getrlimit:");
+	new_rlimit = og_rlimit;
+	new_rlimit.rlim_cur = new_rlimit.rlim_max;
+	if (setrlimit(RLIMIT_NOFILE, &new_rlimit) < 0)
+		die("setrlimit:");
+
 	for (i = 0; i < (int)LENGTH(sig); i++)
 		sigaction(sig[i], &sa, NULL);
 
@@ -2649,6 +2670,7 @@ void
 spawn(const Arg *arg)
 {
 	if (fork() == 0) {
+		restorerlimit();
 		dup2(STDERR_FILENO, STDOUT_FILENO);
 		setsid();
 		execvp(((char **)arg->v)[0], (char **)arg->v);
-- 
2.46.0

