如何设置最大打开文件描述符数

在开发中大型在线项目线上可能会遇到文件句柄数不够的问题,这个时候我们就需要进行内核参数修改。

参数概念

这里我们需要先理清下面几个关联的参数

ulimit

Provides control over the resources available to the shell and to processes started by it, on systems that allow such control.

表示对单一程序的限制,针对当前用户下进程级别的。

ulimit -n
1024

这表示当前用户的每个进程最多允许同时打开1024个文件。这1024个文件中还得除去每个进程必然打开的标准输入,标准输出,标准错误,服务器监听 socket,进程间通讯的unix域socket等文件,那么剩下的可用于客户端socket连接的文件数就只有大概1024-10=1014个左右。也就是说缺省情况下,基于Linux的通讯程序最多允许同时1014个TCP并发连接。

nr_open

This denotes the maximum number of file-handles a process can allocate. Default value is 1024*1024 (1048576) which should be enough for most machines. Actual limit depends on RLIMIT_NOFILE resource limit.

表示单个进程可分配的最大文件数。

file-max

The value in file-max denotes the maximum number of file-handles that the Linux kernel will allocate.When you get lots of error messages about running out of file handles, you might want to increase this limit. Historically,the kernel was able to allocate file handles dynamically, but not to free them again.

表示所有时程最大的文件数。

一般可以用内存大小(kB)的10%来计算

 grep MemTotal /proc/meminfo |awk '{print $2/10}'

参数设置

echo "fs.file-max = 20971520" >>/etc/sysctl.conf
echo "fs.nr_open= 10485760" >>/etc/sysctl.conf
sysctl -p
echo "root soft nofile 6553560"  >>/etc/security/limits.conf 
echo "root hard nofile 6553560" >>/etc/security/limits.conf

注1:sysctl -p 表示使上面的设置生效

注2:以上数值谨供参考,具体需要根据业务&机器状态实际调整

注3:以上设置均为永久生效,临时生效方式请自行检索

注4:上面最后2行设置的ulimit仅对root用户生效,请按需调整

特注:根据之前的参数概念设置时候需要特别注意 soft nofile不能超过 hard nofile 不能超过 nr_open 不能超过 file-max ,相应的如果需要调整也需要联动修改这些参数

还差一点

上面修改完一般就可以了,但是针对修改前就已经运行的程序是不生效的,我们一般首先想到的就是重启程序,但是我们程序可能并不是完美支持平滑重启的,这里我们推荐直接修改运行程序的nofile, ps找到当前程序的pid按需调整执行下面命令即可。

prlimit --pid xxxx --nofile=xxxxx

 

 

 

 

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据