Too many open files 解决方案

Attson Lv3

使用版本

1
2
3
4
5
6
7
8
# uname -a
Linux 5.4.0-52-generic #57-Ubuntu SMP Thu Oct 15 10:57:00 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
# lsb_release -a
Ubuntu 20.04.1 LTS

Linux ecs-w0xX6 3.10.0-957.12.2.el7.x86_64 #1 SMP Tue May 14 21:24:32 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux
# cat /etc/redhat-release
CentOS Linux release 7.6.1810 (Core)

现象

1
accept tcp [::]:3322: accept4: too many open files

解决方案

方案一、 ulimit (用于限制 shell 启动的进程所占用的资源)

1
ulimit -n 102400

注意:

  • ulimit 限制的是当前 shell 进程以及其派生的子进程, 作用范围比较小,可以临时解决在当前shell执行程序的限制
  • ulimit 命令是 很多shell程序的内置命令,如csh、sh等,所以支持的环境会更多
  • 在某些系统没有pam_limits模块的,可以用此命令结合所要执行的命令一起,实现修改程序的文件描述符限制。如 ulimit -n 102400 && ./main

方案二、 更改 /etc/security/limits.conf (该文件为pam 中 pam_limits 模块的默认配置文件)

1
2
3
4
5
6
7
vim /etc/security/limits.conf  
# 在最后加入
* soft nofile 102400
* hard nofile 102400

或者
* - nofile 102400

最前的 * 表示所有用户,可根据需要设置某一用户,例如
root soft nofile 102400
root hard nofile 102400

改完后重新登录就能生效

注意:

方案三、 针对使用supervisor管理的程序

在supervisord的配置文件 /etc/supervisor/supervisord.conf 中 [supervisord] 处添加 minfds = 102400

supervisord configuration

1
2
[supervisord]
minfds = 102400

方案四、/etc/sysctl.conf (该文件为内核配置文件)

当单进程需求数量超过 cat /proc/sys/fs/nr_open
当单机需求数量超过 cat /proc/sys/fs/file-max

按需修改 /etc/sysctl.conf 文件

1
2
fs.file-max=2000500
fs.nr_open=2000500

file-max: 该值为是内核可分配的最大文件数
nr_open: 该值为单个进程可分配的最大文件数

其他

  • 当大家遇到limits修改不生效的时候,请查一下进程是否只是子进程,如果是,再检查是不是受父进程cat /proc/<pid>/limits配置影响

参考

你真知道“Too many open files”?

  • 标题: Too many open files 解决方案
  • 作者: Attson
  • 创建于 : 2020-10-24 15:11:01
  • 更新于 : 2023-10-18 16:13:23
  • 链接: https://attson.github.io/p/too-many-open-file.html
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。
 评论