再谈Linux的ulimit

(测试系统Centos7)centos

测试脚本bash

[root@up01 ~]# cat /tmp/test_ulimit.py 
import sys

def test_n():
    total=[]
    try:
        for i in range(0,100000):
            total.append(open('/tmp/{}-{}'.format('jjkkll',i),'w'))
    except Exception as err:
        print(i, repr(err))

test_n()

关于/etc/security/limits.conf中开篇既有两句话提示app

#This file sets the resource limits for the users logged in via PAM.
#It does not affect resource limits of the system services.

意思就是这里的限制只对通过PAM验证的登录用户有效,并明确说明对开机自启的系统服务(经chkconfig 或systemd控制的开机启动服务)以及 /etc/init.d/rc.local(经试验亦无效) 中的命令无效。ide

另外经验证:同时在/etc/security/limits.conf和/etc/profile中设置不一样的值,/etc/profile中的值最终生效(说明PAM认证在profile以前)测试

那如何在开启及启动的服务中突破系统默认的ulimit值呢?

首相尝试了在/etc/profile中添加对应设置,经测试对开机自启的系统服务/etc/init.d/rc.local仍然无效(而且验证了系统服务的运行时间要早于/etc/init.d/rc.local)centos7

[root@centos7-1 ~]# cat /tmp/log-init 
  (1021, "IOError(24, 'Too many open files')")
  Sat Nov  3 06:35:19 EDT 2018
[root@centos7-1 ~]# cat /tmp/log-rc.local 
  (1021, "IOError(24, 'Too many open files')")
  Sat Nov  3 06:35:25 EDT 2018
[root@centos7-1 ~]# ulimit -n
  3000 
[root@centos7-1 ~]#

并且在/etc/profile中假如ulimit配置(以及任何须要root权限运行的命令),那在以其余用户登录时,就会报一条“无权限”类错误。是由于 /etc/profile 在系统启动过程当中执行的时机:(倒数第一或 第二步)即任何用户登录前才/先执行/etc/profile,而后再是 ~/.bash_profile(如有的话)code

那么到底该如何解决上面的问题呢?

后经查明,/etc/init.d/xxxx 以及/etc/rc.loca中的命令都是centos7以前的产物,centos7以后系统引导及服务管理由sysV改成了systemd,而systemd对于ulimit中指定的各种限制是在xxxx.service文件中设置的,这也是推荐的方式。例如 LimitNOFILE=65536。orm

可是若是非要在/etc/init.d/xxxx以及/etc/rc.local中突破默认限制的话

  1. 对于/etc/rc.local,有以下方法
    在 /usr/lib/systemd/system/rc-local.service 的 [Service] 段下增长相应配置,如 LimitNOFILE=3000
  2. 对于/etc/init.d/xxx
    centos7 中还没找到解决方案(其实执着于此也无心义,由于7的服务管理是systemd)
    centos6 中科经过在/etc/init.d/functions中增长一句ulimit -n 65536(以及其余设置)来解决

通过实验看下来,发现了一个特色,一个进程能打开的文件描述符老是比设置的nofile值小3,这是由于还有0,1,2 三个标准输入,输出,错误的存在。进程

相关文章
相关标签/搜索