Linux上修改open files数目

Linux系统上默认的open files数目为1024, 有时应用程序会报Too many open files的错误,是因为open files 数目不够。

用 ulimit -a 命令可以查看 系统对各种参数的限制;
 
# ulimit -a
core file size          (blocks, -c) 0
data seg size          (kbytes, -d) unlimited
scheduling priority            (-e) 0
file size              (blocks, -f) unlimited
pending signals                (-i) 257648
max locked memory      (kbytes, -l) 64
max memory size        (kbytes, -m) unlimited
open files                      (-n) 4096
pipe size            (512 bytes, -p) 8
POSIX message queues    (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) unlimited
cpu time              (seconds, -t) unlimited
max user processes              (-u) unlimited
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited
由上面可以知道 open files 当前限制为 4096,ok,我们可以修改稍微大一点;
当你把open files的值增大到一定程度,你的Too many open files就不会再出现了。
 
修改方法:
(1)ulimit -HSn 102400
这只是在当前终端有效,退出之后,open files 又变为默认值。
(2)将ulimit -HSn 102400写到/etc/profile中,因为每次登录终端时,都会自动执行/etc/profile。
(3)令修改open files的数值永久生效,则必须修改配置文件:/etc/security/limits.conf. 在这个文件后加上:
* soft nofile 102400
* hard nofile 102400
这种方法需要重启机器才能生效。
(4)为了让一个程序的open files数目扩大,可以在启动脚本前面加上(1)中的命令。当程序是一个daemon时,可能这种方法无效,没有终端了。
 
影响open files数值的还有一个内核参数file-max,这是Linuxt系统的总限制。可以通过如下文式查看:
cat /proc/sys/fs/file-max
或者
sysctl -a | grep fs.file-max
 
对于服务器可以采用如下方法修改file-max:
(1)重启机器后恢复为默认值
echo 34166 > /proc/sys/fs/file-max
或者
sysctl -w "fs.file-max=34166"
(2)修改配置文件/etc/sysctl.conf, 在最后加上一行:
fs.file-max = 34166
然后sysctl -p 生效 或者 重启机器以后永久生效。

推荐阅读:

相关推荐