Postfix3.3.1
open_limit.c
[詳解]
1 /*++
2 /* NAME
3 /* open_limit 3
4 /* SUMMARY
5 /* set/get open file limit
6 /* SYNOPSIS
7 /* #include <iostuff.h>
8 /*
9 /* int open_limit(int limit)
10 /* DESCRIPTION
11 /* The \fIopen_limit\fR() routine attempts to change the maximum
12 /* number of open files to the specified limit. Specify a null
13 /* argument to effect no change. The result is the actual open file
14 /* limit for the current process. The number can be smaller or larger
15 /* than the requested limit.
16 /* DIAGNOSTICS
17 /* open_limit() returns -1 in case of problems. The errno
18 /* variable gives hints about the nature of the problem.
19 /* LICENSE
20 /* .ad
21 /* .fi
22 /* The Secure Mailer license must be distributed with this software.
23 /* AUTHOR(S)
24 /* Wietse Venema
25 /* IBM T.J. Watson Research
26 /* P.O. Box 704
27 /* Yorktown Heights, NY 10598, USA
28 /*--*/
29 
30 /* System libraries. */
31 
32 #include "sys_defs.h"
33 #include <sys/time.h>
34 #include <sys/resource.h>
35 #include <errno.h>
36 
37 #ifdef USE_MAX_FILES_PER_PROC
38 #include <sys/sysctl.h>
39 #define MAX_FILES_PER_PROC "kern.maxfilesperproc"
40 #endif
41 
42 /* Application-specific. */
43 
44 #include "iostuff.h"
45 
46  /*
47  * 44BSD compatibility.
48  */
49 #ifndef RLIMIT_NOFILE
50 #ifdef RLIMIT_OFILE
51 #define RLIMIT_NOFILE RLIMIT_OFILE
52 #endif
53 #endif
54 
55 /* open_limit - set/query file descriptor limit */
56 
57 int open_limit(int limit)
58 {
59 #ifdef RLIMIT_NOFILE
60  struct rlimit rl;
61 #endif
62 
63  if (limit < 0) {
64  errno = EINVAL;
65  return (-1);
66  }
67 #ifdef RLIMIT_NOFILE
68  if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
69  return (-1);
70  if (limit > 0) {
71 
72  /*
73  * MacOSX incorrectly reports rlim_max as RLIM_INFINITY. The true
74  * hard limit is finite and equals the kern.maxfilesperproc value.
75  */
76 #ifdef USE_MAX_FILES_PER_PROC
77  int max_files_per_proc;
78  size_t len = sizeof(max_files_per_proc);
79 
80  if (sysctlbyname(MAX_FILES_PER_PROC, &max_files_per_proc, &len,
81  (void *) 0, (size_t) 0) < 0)
82  return (-1);
83  if (limit > max_files_per_proc)
84  limit = max_files_per_proc;
85 #endif
86  if (limit > rl.rlim_max)
87  rl.rlim_cur = rl.rlim_max;
88  else
89  rl.rlim_cur = limit;
90  if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
91  return (-1);
92  }
93  return (rl.rlim_cur);
94 #endif
95 
96 #ifndef RLIMIT_NOFILE
97  return (getdtablesize());
98 #endif
99 }
100 
int open_limit(int limit)
Definition: open_limit.c:57