]> git.ozlabs.org Git - ccan/blob - ccan/closefrom/closefrom.h
closefrom: Close all file descriptors above a certain value.
[ccan] / ccan / closefrom / closefrom.h
1 /* CC0 license (public domain) - see LICENSE file for details */
2 #ifndef CCAN_CLOSEFROM_H
3 #define CCAN_CLOSEFROM_H
4 #include "config.h"
5 #include <stdbool.h>
6
7 #if HAVE_CLOSEFROM
8 /* BSD.  */
9 #include <unistd.h>
10 /* Solaris.  */
11 #include <stdlib.h>
12
13 static inline
14 bool closefrom_may_be_slow(void)
15 {
16         return 0;
17 }
18
19 static inline
20 void closefrom_limit(unsigned int limit)
21 {
22 }
23
24 #else /* !HAVE_CLOSEFROM */
25
26 /**
27  * closefrom - Close all open file descriptors, starting
28  * at fromfd onwards.
29  * @fromfd: the first fd to close; it and all higher file descriptors
30  * will be closed.
31  *
32  * This is not multithread-safe: other threads in the same process
33  * may or may not open new file descriptors in parallel to this call.
34  * However, the expected use-case is that this will be called in a
35  * child process just after fork(), meaning the child process is still
36  * single-threaded.
37  */
38 void closefrom_(int fromfd);
39 /* In case the standard library has it, but declared in some
40  * *other* header we do not know of yet, we use closefrom_ in
41  * the actual name the linker sees.
42  */
43 #define closefrom closefrom_
44
45 /**
46  * closefrom_may_be_slow - check if the closefrom() function could
47  * potentially take a long time.
48  *
49  * The return value is true if closefrom() is emulated by
50  * looping from fromfd to sysconf(_SC_OPEN_MAX), which can be
51  * very large (possibly even INT_MAX on some systems).
52  * If so, you might want to use setrlimit to limit _SC_OPEN_MAX.
53  * If this returns false, then closefrom is efficient and you do not
54  * need to limit the number of file descriptors.
55  *
56  * You can use closefrom_limit to perform the limiting based on
57  * closefrom_may_be_slow.
58  * This API is exposed in case you want to output to debug logs or
59  * something similar.
60  */
61 bool closefrom_may_be_slow(void);
62
63 /**
64  * closefrom_limit - If closefrom_may_be_slow(), lower the limit on
65  * the number of file descriptors we keep open, to prevent closefrom
66  * from being *too* slow.
67  * @limit: 0 to use a reasonable default of 4096, or non-zero for the
68  * limit you prefer.
69  *
70  * This function does nothing if closefrom_may_be_slow() return false.
71  *
72  * This function only *lowers* the limit from the hard limit set by
73  * root before running this program.
74  * If the limit is higher than the hard limit, then the hard limit is
75  * respected.
76  */
77 void closefrom_limit(unsigned int limit);
78
79 #endif /* !HAVE_CLOSEFROM */
80
81 #endif /* CCAN_CLOSEFROM_H */