1 #include <errno.h>
2 #include <fcntl.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <sys/resource.h>
6 #include <unistd.h>
7 #include "fdleak.h"
8
main(int argc,char ** argv)9 int main(int argc, char **argv)
10 {
11 struct rlimit oldrlim;
12 struct rlimit newrlim;
13 int fd;
14
15 CLOSE_INHERITED_FDS;
16
17 if (getrlimit(RLIMIT_NOFILE, &oldrlim) < 0)
18 {
19 perror("getrlimit");
20 exit(1);
21 }
22
23 newrlim.rlim_cur = oldrlim.rlim_cur / 2;
24 newrlim.rlim_max = oldrlim.rlim_max;
25
26 if (setrlimit(RLIMIT_NOFILE, &newrlim) < 0)
27 {
28 perror("setrlimit");
29 exit(1);
30 }
31
32 if (getrlimit(RLIMIT_NOFILE, &newrlim) < 0)
33 {
34 perror("getrlimit");
35 exit(1);
36 }
37
38 if (newrlim.rlim_cur != oldrlim.rlim_cur / 2)
39 {
40 fprintf(stderr, "rlim_cur is %llu (should be %llu)\n",
41 (unsigned long long)newrlim.rlim_cur,
42 (unsigned long long)oldrlim.rlim_cur / 2);
43 }
44
45 if (newrlim.rlim_max != oldrlim.rlim_max)
46 {
47 fprintf(stderr, "rlim_max is %llu (should be %llu)\n",
48 (unsigned long long)newrlim.rlim_max,
49 (unsigned long long)oldrlim.rlim_max);
50 }
51
52 newrlim.rlim_cur -= 3; /* allow for stdin, stdout and stderr */
53
54 while (newrlim.rlim_cur-- > 0)
55 {
56 if (open("/dev/null", O_RDONLY) < 0)
57 {
58 perror("open");
59 }
60 }
61
62 if ((fd = open("/dev/null", O_RDONLY)) >= 0)
63 {
64 fprintf(stderr, "open succeeded with fd %d - it should have failed!\n", fd);
65 }
66 else if (errno != EMFILE)
67 {
68 perror("open");
69 }
70
71 exit(0);
72 }
73