Search code examples
clinuxposixbsd

Portable equivalent of OPEN_MAX


nftw wants a parameter for number of file handles to use, and doesn't seem to have a way to say 'as many as possible'. Specifying 255 seems to work on Linux, but fails on BSD. Apparently OPEN_MAX is the recommended solution on BSD, but I can't use this as it doesn't work on Linux.

Is there a portable equivalent of OPEN_MAX that will work on both Linux and BSD?

Alternatively, is there a portable number, some number large enough to not slow things down, that is portable for practical purposes (ideally specified in POSIX, or at least that will work on every Unix-like system with significant market share)?


Solution

  • Advanced Programming in the Unix Environment, 2nd Ed gives us the following code which should work everywhere; though it is pretty clever, I think it is a little unfortunate it doesn't also check the rlimits of the process, since the rlimits can further constrain how many open files a process may use. That aside, here's the code from The Master:

    #ifdef  OPEN_MAX
    static long openmax = OPEN_MAX;
    #else
    static long openmax = 0;
    #endif
    
    /*
     * If OPEN_MAX is indeterminate, we're not
     * guaranteed that this is adequate.
     */
    #define OPEN_MAX_GUESS  256
    
    long
    open_max(void)
    {
        if (openmax == 0) {     /* first time through */
            errno = 0;
            if ((openmax = sysconf(_SC_OPEN_MAX)) < 0) {
                if (errno == 0)
                    openmax = OPEN_MAX_GUESS;   /* it's indeterminate */
                else
                    err_sys("sysconf error for _SC_OPEN_MAX");
            }
        }
    
        return(openmax);
    }
    

    (err_sys() is provided in the apue.h header with the sources -- should be easy to code a replacement for your routine.)