Linux(CentOS 7)修改max open files的值

新安装的linux系统允许每个程序的最大打开文件数默认是1024,可以通过ulimit -n命令来查看,查看全部限制,则可以使用命令ulimit -a

复制代码
[root@test ~]# 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) 63399
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 63399
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
复制代码
修改这个值,可以有这些方法

系统全局参数file-max

cat /proc/sys/fs/file-max
1613096

系统级别的限制

如果是系统服务

编辑服务配置文件:/usr/lib/systemd/system/SERVICE_NAME.service,在[Service]段添加行:LimitNOFILE=65535,下面是nginx的示例:

复制代码
vim nginx.service

[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network-online.target remote-fs.target nss-lookup.target
Wants=network-online.target

[Service]
Type=forking
PIDFile=/opt/web_engine/nginx/run/nginx.pid
ExecStartPre=/opt/web_engine/nginx/sbin/nginx -t -c /opt/web_engine/nginx/conf/nginx.conf
ExecStart=/opt/web_engine/nginx/sbin/nginx -c /opt/web_engine/nginx/conf/nginx.conf
ExecReload=/bin/kill -s HUP $MAINPID
ExecStop=/bin/kill -s TERM $MAINPID
LimitNOFILE=65535

[Install]
WantedBy=multi-user.target
复制代码

运行systemctl daemon-reload让配置文件激活,再重启服务,即可让配置生效

查看配置是否生效:ps -ef|grep nginx  得到nginx主进程的PID
cat /proc/$PID/limits  如果看到Max open files 65535 65535 files 则说明配置已生效

临时修改,重启后失效,不对运行中程序生效

运行命令:ulimit -HSn 65535  该命令也等同于ulimit -n 65535
H为硬限制,S为软限制,需要注意的是,退出登录后,将失效

永久修改,需要重启系统

一般方式:
vim /etc/security/limits.conf  添加
* soft nofile 65535
* hard nofile 65535
*代表用户,全部用户或用户组
复制代码
 #MySQL env
mysql soft nproc 2047
mysql hard nproc 16384
mysql soft nofile 1024
mysql hard nofile 65536
mysql soft stack 10240
复制代码

上面的nproc是允许创建的子进程数目,不能过大,防止accidental fork bombs,一般4096比较合适

高级一点的做法:
将配置写到/etc/security/limits.d/nofile.conf  这种不直接写到系统limits文件中,当limits需要升级时,不会丢失配置
另外一种做法:
在系统启动过程中,执行一次ulimit -SHn 65533,比如可以写到/etc/rc.local中,或者/etc/profile中等

动态修改运行中程序的值

不安全的作法,但是在不可中止运行中程序的时候,会很管用
直接修改文件:/proc/$PID/limits  的这一行Max open files 65535 65535 files

命令行操作:

1
prlimit --pid 24340 --nofile=65535:65535
原文地址:https://www.cnblogs.com/weifeng1463/p/13926451.html