From: Willy Tarreau Date: Thu, 21 Feb 2019 21:19:17 +0000 (+0100) Subject: MINOR: fd: add a new my_closefrom() function to close all FDs X-Git-Tag: v2.0-dev1~22 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=2d7f81b809ec469b82ac724c31e5c1cc4f444b9b;p=thirdparty%2Fhaproxy.git MINOR: fd: add a new my_closefrom() function to close all FDs 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. --- diff --git a/include/proto/fd.h b/include/proto/fd.h index 81aea87bc8..14c22201c7 100644 --- a/include/proto/fd.h +++ b/include/proto/fd.h @@ -61,6 +61,9 @@ void fd_delete(int fd); */ void fd_remove(int fd); +/* close all FDs starting from */ +void my_closefrom(int start); + /* disable the specified poller */ void disable_poller(const char *poller_name); diff --git a/src/fd.c b/src/fd.c index 9434c63003..92d093cb63 100644 --- a/src/fd.c +++ b/src/fd.c @@ -149,6 +149,7 @@ #include #include #include +#include #include #include @@ -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 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) {