本文打算探讨两种设置方法,一种是在程序中动态设置,一种是在程序启动前的静态设置。

先说静态设置(具体设置见:参考csdn的一篇文章):

1,在/etc/security/limits.conf中修改或者添加进程可打开文件数的软硬设置,

* soft nofile 10240

* hard nofile 10240


2,在/etc/pam.d/login中添加

session required /lib/security/pam_limits.so

注:这个配置的最近的一两次修改,导致系统启不来了,还得用救援模式恢复,

还是不要设置这个了,效果还是和设置后一样的(需要重启机子)


3,查看linux系统最在打开文件数限制,cat /proc/sys/fs/file-max,根据需要,修改此设置:

echo 222222 > /proc/sys/fs/file-max

echo 222222 > /proc/sys/fs/nr_open

# /proc/sys/fs/file-max 系统所有进程可打开的最大文件数目

# /proc/sys/fs/nr_open 是单个进程可分配的最大文件数

# ulimit -f 网上有说是设置可创建(不是打开)的文件大小数目,

# man 一下看到的是本shell及其子shell可以打开的文件数目

# 为了避免重启后失效,

echo fs.file-max=222222 >> /etc/sysctl.conf

echo fs.nr_open=222222 >> /etc/sysctl.conf

# 立即生效

sysctl -p


以上步骤设置好后,可以用 ulimit -n 查看效果


4,修改系统可使用端口范围,/etc/sysctl.conf

    net.ipv4.ip_local_port_range = 1024 65000

    #net.ipv4.ip_conntrack_max = 10240,好像不存在本配置

修改后,使生效,sysctl -p


参考来源:

http://www.cnblogs.com/zengkefu/p/5635153.html

http://www.cnblogs.com/TonyXiaoClub/p/4747736.html



动态设置:

#include <sys/capability.h>
#include <sys/prctl.h>
#include <sys/resource.h>
#include <iostream>
#include <errno.h>
using namespace std;

int main(int argc, char *argv[])
{
    int ret = prctl(PR_CAPBSET_READ,CAP_SYS_RESOURCE,0,0);
    if (ret == 1)
        cout<<"CAP_SYS_RESOURCE enabled"<<endl;
    else
        cout<<"CAP_SYS_RESOURCE disabled"<<endl;

    struct rlimit rt,rt_new;
    ret = getrlimit(RLIMIT_NOFILE,&rt);
    if (ret != 0)
    {
        cout<<"getrlimit error"<<endl;
        return 0;
    }
    cout<<"old soft limit:"<<rt.rlim_cur<<"\told hard limit:"<<rt.rlim_max<<endl;

    rt.rlim_cur = rt.rlim_max = 40960000;
    ret = setrlimit(RLIMIT_NOFILE,&rt);
    if (ret != 0)
    {
        cout<<"setrlimt error:"<<errno<<endl;
        cap_t caps = cap_init();
        cap_value_t caplist[2] = {CAP_SYS_RESOURCE,CAP_SETPCAP};
        unsigned int num_caps = 2;
        cap_set_flag(caps,CAP_EFFECTIVE,num_caps,caplist,CAP_SET);
        cap_set_flag(caps,CAP_INHERITABLE,num_caps,caplist,CAP_SET);
        cap_set_flag(caps,CAP_PERMITTED,num_caps,caplist,CAP_SET);
        if (cap_set_proc(caps))
        {
            cout<<"cap_set_proc failed"<<endl;
            return 0;
        }
        ret = setrlimit(RLIMIT_NOFILE,&rt);
        if (ret != 0)
        {
            cout<<"setrlimit error:"<<errno<<endl;
            return 0;
        }
    }

    ret = getrlimit(RLIMIT_NOFILE,&rt_new);
    if (ret != 0)
    {
        cout<<"getrlimit error:"<<errno<<endl;
        return 0;
    }
    cout<<"new soft limit:"<<rt_new.rlim_cur<<"\tnew hard limit:"<<rt_new.rlim_max<<endl;
    return 0;
}

编译前需要安装:libcap-devel

编译:g++ file.cpp -lcap

运行结果,设置不成功。