修改linux系统下的最大文件描述符限制

linux下最大文件描述符的限制有两个方面,一个是进程级的限制,另外一个则是系统级限制。

1. 系统级的限制

/proc/sys/fs/file-max是系统中的所有进程总共可以同时打开的文件数量,可以通过修改内核参数来更改该限制:sysctl -w fs.file-max=102400。但是,使用sysctl命令更改是临时的,如果想永久更改需要在/etc/sysctl.conf添加fs.file-max=102400,保存退出后使用sysctl -p 命令使其生效。

/proc/sys/fs/file-max:This file defines a system-wide limit on the number of open files for all processes. (See also setrlimit(2), which can be used by a process to set the per-process limit, RLIMIT_NOFILE, on the number of files it may open.) If you get lots of error messages about running out of file handles, try increasing this value: echo 100000 > /proc/sys/fs/file-max. The kernel constant NR_OPEN imposes an upper limit on the value that may be placed in file-max. If you increase /proc/sys/fs/file-max, be sure to increase /proc/sys/fs/inode-max to 3-4 times the new value of /proc/sys/fs/file-max, or you will run out of inodes.

2. 进程级的限制

修改一个进程能够同时打开的文件数量限制有两种方式:(1)通过bash的内置命令ulimit (2)在程序中调用setrlimit函数

(1)ulimit is a bash built_in command. It provides control over the resources available to the shell and to processes started by it.
执行ulimit -n命令可以看到本次登录的shell会话的文件描述符的限制,一般情况下是1024。当然可以通过ulimit -SHn 102400 命令来修改该限制。
(2) The getrlimit() and setrlimit() system calls get and set resource limits respectively. Each resource has an associated soft and hard limit, as defined by the rlimit structure:

struct rlimit {
rlim_t rlim_cur; /* Soft limit */
rlim_t rlim_max; /* Hard limit (ceiling for rlim_cur) */
};

The soft limit is the value that the kernel enforces for the corresponding resource. The hard limit acts as a ceiling for the soft limit: an unprivileged process may only set its soft limit to a value in the range from 0 up to the hard limit, and (irreversibly) lower its hard limit. A privileged process may make arbitrary changes to either limit value. The value RLIM_INFINITY denotes no limit on a resource.

不管通过ulimit还是setrlimit来修改限制,都只能对当前进程及其子进程有效。而且它们都会受到/etc/security/limits.conf文件中的数量限制。如下所示,

vi /etc/security/limits.conf
xiaohua hard nofile 100
xiaohua soft nofile 100

则用户xiaohua的每个进程能够同时打开的文件数量的上限是100,通过ulimit和setrlimit的修改的上限值不能超过它。而且可以看出,其实/etc/security/limits.conf是用户级的限制,能够限制某个用户或者用户组的每个进程能够同时打开的文件数量的上限。修改该文件,保存退出后重新登录,里面设置的值才会生效。