]> git.ozlabs.org Git - ccan/blob - ccan/closefrom/_info
28f903a4714093d59db95314adc99a2d6ecb301e
[ccan] / ccan / closefrom / _info
1 #include "config.h"
2 #include <stdio.h>
3 #include <string.h>
4
5 /**
6  * closefrom - close all fds starting from specified fd.
7  *
8  * This code is an example of what to do in a child process to
9  * ensure that none of the (possibly sensitive) file descriptors
10  * in the parent remain in the child process.
11  *
12  * License: CC0 (Public domain)
13  * Author: ZmnSCPxj jxPCSnmZ <ZmnSCPxj@protonmail.com>
14  *
15  * Example:
16  * #include <ccan/closefrom/closefrom.h>
17  * #include <ccan/err/err.h>
18  * #include <stdio.h>
19  * #include <sys/resource.h>
20  * #include <sys/time.h>
21  * #include <sys/types.h>
22  * #include <sys/wait.h>
23  * #include <unistd.h>
24  *
25  * int main(int argc, char **argv)
26  * {
27  *      pid_t child;
28  *
29  *      // If being emulated, then we might end up
30  *      // looping over a large _SC_OPEN_MAX
31  *      // (Some systems have it as INT_MAX!)
32  *      // If so, closefrom_limit will lower this limit
33  *      // to a value you specify, or if given 0 will
34  *      // limit to 4096.
35  *      // Call this as early as possible.
36  *      closefrom_limit(0);
37  *
38  *      // If we limited, we can query this so we can
39  *      // print it in debug logs or something.
40  *      if (close_from_may_be_slow())
41  *              printf("we limited ourselves to 4096 fds.\n");
42  *
43  *      child = fork();
44  *      if (child < 0)
45  *              err(1, "Forking");
46  *      if (child == 0) {
47  *              closefrom(STDERR_FILENO + 1);
48  *              // Insert your *whatever* code here.
49  *              _exit(0);
50  *      }
51  *
52  *      waitpid(child, NULL, 0);
53  *
54  *      return 0;
55  * }
56  *
57  */
58 int main(int argc, char *argv[])
59 {
60         /* Expect exactly one argument */
61         if (argc != 2)
62                 return 1;
63
64         if (strcmp(argv[1], "depends") == 0) {
65                 return 0;
66         }
67
68         return 1;
69 }