简体   繁体   中英

How to set the max number of open files in only one process?

OS controls the max number of open file discripters.

Is there any method that only a process sets a specific the max number of openfiles and, other processes only can use the traditional default max number of openfiles?

Yes.

A process can use getrlimit and setrlimit to limit the number of files it may open.

It operates on the current process.

A program that uses this can do a fork , use getrlimit/setrlimit and then do (eg) execvp to limit a child program.


Here is some code. The count reported will be 3 less because stdin/stdout/stderr are open.

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/resource.h>

void
show(struct rlimit *rlim,const char *who)
{

    printf("rlim_cur=%d rlim_max=%d [%s]\n",
        rlim->rlim_cur,rlim->rlim_max,who);
}

int
main(int argc,char **argv)
{
    int err;
    struct rlimit rlim;

    --argc;
    ++argv;

    setlinebuf(stdout);
    setlinebuf(stderr);

    err = getrlimit(RLIMIT_NOFILE,&rlim);
    if (err < 0) {
        perror("getrlimit");
        exit(1);
    }

    show(&rlim,"original");

    if (argc > 0) {
        rlim.rlim_cur = atoi(*argv);
        err = setrlimit(RLIMIT_NOFILE,&rlim);

        if (err < 0) {
            perror("setrlimit");
            exit(1);
        }

        err = getrlimit(RLIMIT_NOFILE,&rlim);
        if (err < 0) {
            perror("setrlimit");
            exit(1);
        }
        show(&rlim,"setrlimit");
    }

    int count = 0;
    while (1) {
        int fd = open("/dev/null",O_RDONLY);
        if (fd < 0) {
            perror("open");
            break;
        }
        ++count;
    }

    printf("max open files: %d\n",count);

    return 0;
}

Normal output:

rlim_cur=1024 rlim_max=4096 [original]
open: Too many open files
max open files: 1021

Output with arg of 17:

rlim_cur=1024 rlim_max=4096 [original]
rlim_cur=17 rlim_max=4096 [setrlimit]
open: Too many open files
max open files: 14

One way to change resource limits of a particular process using prlimit ,

prlimit --pid <PID> --nofile=1024:4095

Internally prlimit makes use of system call setrlimit() to set the limits.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM