Search code examples
clinuxfilespawn

Maximum number of files that can be open and processes that can be spawned


When I was running a program that modifies files, and had loaded exactly 1000 files, the program aborted with the message:

Process launching failed: Too many open files

Where can I find the C constant to use in my code to figure out the maximum number of files that can be open and processes that can be spawned all at once?


Solution

  • On POSIX-compatible systems, you can use the getrlimit function with the RLIMIT_NOFILE parameter.

    #include <sys/resource.h>
    
    rlim_t get_open_files_limit() {
        struct rlimit limit;
        getrlimit(RLIMIT_NOFILE, &limit);
        return limit.rlim_cur;
    }
    

    Some systems (Linux, BSD, maybe others?) define an RLIMIT_NPROC on top of this which can tell you the maximum number of processes that the user is allowed to create. See FreeBSD-specific documentation, Linux-specific documentation.