Search code examples
clinuxfile-descriptor

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?


Solution

  • 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 (e.g.) 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