Linux 修改文件描述符

linux系统默认open files数目为1024, 有时应用程序会报Too many open files的错误,是因为open files 数目不够。这就需要修改ulimit和file-max。特别是提供大量静态文件访问的web服务器,缓存服务器(如squid), 更要注意这个问题。
网上的教程,都只是简单说明要如何设置ulimit和file-max, 但这两者之间的关系差别,并没有仔细说明。

查看

root@aliyun:~# ulimit -n
65535

说明

file-max的含义

man proc,可得到file-max的描述:

/proc/sys/fs/file-maxThis file defines a system-wide limit on the number of open files for all processes. (Seealso 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 messagesabout running out of file handles, try increasing this value:即file-max是设置 系统所有进程一共可以打开的文件数量 。同时一些程序可以通过setrlimit调用,设置每个进程的限制。如果得到大量使用完文件句柄的错误信息,是应该增加这个值。也就是说,这项参数是系统级别的。

ulimit

Provides control over the resources available to the shell and to processes started by it, on systems that allow such control.即设置当前shell以及由它启动的进程的资源限制。显然,对服务器来说,file-max, ulimit都需要设置,否则就可能出现文件描述符用尽的问题修改:

修改

1.临时修改

root@aliyun:~# ulimit -HSn 1000000
root@aliyun:~# ulimit -n
1000000

2.永久修改

root@aliyun:~# vim /etc/security/limits.conf

修改这些参数的值

root soft nofile 65535
root hard nofile 65535
* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535
* soft nofile 65535
* hard nofile 65535

此外还需要文件的打开数,

1.临时修改

root@aliyun:~# echo  “100000” >> /proc/sys/fs/file-max
65535

2.永久

# vim /etc/sysctl.conf, 加入以下内容,重启生效
fs.file-max = 6553560

其他说明

1.为了让一个程序的open files数目扩大,可以在启动脚本前面加上ulimit -HSn 102400命令。但当程序是一个daemon时,可能这种方法无效,因为没有终端。

2.如果某项服务已经启动,再动态调整ulimit是无效的,特别是涉及到线上业务就更麻烦了。
这时,可以考虑通过修改/proc/’程序pid’/limits来实现动态修改!!!