]> git.ipfire.org Git - thirdparty/haproxy.git/commitdiff
MINOR: fd: add a new my_closefrom() function to close all FDs
authorWilly Tarreau <w@1wt.eu>
Thu, 21 Feb 2019 21:19:17 +0000 (22:19 +0100)
committerWilly Tarreau <w@1wt.eu>
Thu, 21 Feb 2019 21:19:17 +0000 (22:19 +0100)
This is a naive implementation of closefrom() which closes all FDs
starting from the one passed in argument. closefrom() is not provided
on all operating systems, and other versions will follow.

include/proto/fd.h
src/fd.c

index 81aea87bc8f0db2a0cb6ec5ccc05f80461bdcde1..14c22201c7d102fe6a05a6de332eede8519c6256 100644 (file)
@@ -61,6 +61,9 @@ void fd_delete(int fd);
  */
 void fd_remove(int fd);
 
+/* close all FDs starting from <start> */
+void my_closefrom(int start);
+
 /* disable the specified poller */
 void disable_poller(const char *poller_name);
 
index 9434c630031c93dc03d92784ca0760b104885b0f..92d093cb633fb51d7247c8c1a73789c6fac07a0e 100644 (file)
--- a/src/fd.c
+++ b/src/fd.c
 #include <unistd.h>
 #include <fcntl.h>
 #include <sys/types.h>
+#include <sys/resource.h>
 
 #include <common/compat.h>
 #include <common/config.h>
@@ -460,6 +461,27 @@ void fd_process_cached_events()
        fdlist_process_cached_events(&fd_cache);
 }
 
+/* This is a portable implementation of closefrom(). It closes all open file
+ * descriptors starting at <start> and above. This is a naive version for use
+ * when the operating system provides no alternative.
+ */
+void my_closefrom(int start)
+{
+       struct rlimit limit;
+       int nbfds;
+
+       if (getrlimit(RLIMIT_NOFILE, &limit) == 0)
+               nbfds = limit.rlim_cur;
+       else
+               nbfds = 0;
+
+       if (nbfds <= 0)
+               nbfds = 1024; /* safe limit */
+
+       while (start < nbfds)
+               close(start++);
+}
+
 /* disable the specified poller */
 void disable_poller(const char *poller_name)
 {