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/* Application-specific. */
38
39#include "iostuff.h"
40
41 /*
42  * 44BSD compatibility.
43  */
44#ifndef RLIMIT_NOFILE
45#ifdef RLIMIT_OFILE
46#define RLIMIT_NOFILE RLIMIT_OFILE
47#endif
48#endif
49
50/* open_limit - set/query file descriptor limit */
51
52int     open_limit(int limit)
53{
54#ifdef RLIMIT_NOFILE
55    struct rlimit rl;
56#endif
57
58    if (limit < 0) {
59	errno = EINVAL;
60	return (-1);
61    }
62#ifdef RLIMIT_NOFILE
63    if (getrlimit(RLIMIT_NOFILE, &rl) < 0)
64	return (-1);
65    if (limit > 0) {
66	if (limit > rl.rlim_max)
67	    rl.rlim_cur = rl.rlim_max;
68	else
69	    rl.rlim_cur = limit;
70	if (setrlimit(RLIMIT_NOFILE, &rl) < 0)
71	    return (-1);
72    }
73    return (rl.rlim_cur);
74#endif
75
76#ifndef RLIMIT_NOFILE
77    return (getdtablesize());
78#endif
79}
80
81