1 /* $Id$ */
2
3 /*
4 *
5 * Copyright (C) 1998 David Mazieres (dm@uun.org)
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License as
9 * published by the Free Software Foundation; either version 2, or (at
10 * your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
20 * USA
21 *
22 */
23
24
25 #ifndef FDLIM_H
26 #define FDLIM_H
27
28 #include <unistd.h>
29 #include <sys/types.h>
30 #include <sys/time.h>
31 #include <sys/resource.h>
32
33 #define FDLIM_MAX 0x10000
34
35 static int
fdlim_get(int hard)36 fdlim_get (int hard)
37 {
38 #ifdef RLIMIT_NOFILE
39 struct rlimit rlfd;
40 if (getrlimit (RLIMIT_NOFILE, &rlfd) < 0)
41 return -1;
42 #ifdef RLIM_INFINITY /* not defined on HPSUX */
43 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
44 return FDLIM_MAX;
45 else
46 #endif /* RLIM_INFINITY */
47 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
48 #else /* !RLIMIT_NOFILE */
49 #ifdef HAVE_GETDTABLESIZE
50 return getdtablesize ();
51 #else /* !HAVE_GETDTABLESIZE */
52 #ifdef _SC_OPEN_MAX
53 return (sysconf (_SC_OPEN_MAX));
54 #else /* !_SC_OPEN_MAX */
55 #ifdef NOFILE
56 return (NOFILE);
57 #else /* !NOFILE */
58 return 25;
59 #endif /* !NOFILE */
60 #endif /* !_SC_OPEN_MAX */
61 #endif /* !HAVE_GETDTABLESIZE */
62 #endif /* !RLIMIT_NOFILE */
63 }
64
65 static int
fdlim_set(rlim_t lim,int hard)66 fdlim_set (rlim_t lim, int hard)
67 {
68 #ifdef RLIMIT_NOFILE
69 struct rlimit rlfd;
70 if (lim <= 0)
71 return -1;
72 if (getrlimit (RLIMIT_NOFILE, &rlfd) < 0)
73 return -1;
74
75 #ifdef RLIMIT_INFINITY
76 if (lim >= FDLIM_MAX)
77 lim = RLIM_INFINITY;
78 #endif /* RLIMIT_INFINITY */
79 switch (hard) {
80 case 0:
81 rlfd.rlim_cur = (lim <= rlfd.rlim_max) ? lim : rlfd.rlim_max;
82 break;
83 case 1:
84 rlfd.rlim_cur = lim;
85 if (lim > rlfd.rlim_max)
86 rlfd.rlim_max = lim;
87 break;
88 case -1:
89 rlfd.rlim_max = lim;
90 if (rlfd.rlim_cur > lim)
91 rlfd.rlim_cur = lim;
92 break;
93 default:
94 #ifdef assert
95 assert (0);
96 #else /* !assert */
97 return -1;
98 #endif /* !assert */
99 }
100
101 if (setrlimit (RLIMIT_NOFILE, &rlfd) < 0)
102 return -1;
103 return 0;
104 #else /* !RLIMIT_NOFILE */
105 return -1;
106 #endif /* !RLIMIT_NOFILE */
107 }
108
109 #endif /* FDLIM_H */
110