cmacosfile-descriptorsetrlimit

Changing file descriptor limit in C (OSX)


I want to increase the maximum number of file descriptors available to my C program, which is running on OSX 10.7. I've added the following code to my project, but it fails!

struct rlimit limit;
if(getrlimit(RLIMIT_NOFILE, &limit))
{
    perror("Failed to get limit");
    return -1;
}

printf("%llu, %llu\n", limit.rlim_cur, limit.rlim_max);
limit.rlim_cur *= 4;
printf("%llu, %llu\n", limit.rlim_cur, limit.rlim_max);

if(setrlimit(RLIMIT_NOFILE, &limit))
{
    perror("Failed to set limit");
    return -1;
}

It prints this the log:

4864, 9223372036854775807
19456, 9223372036854775807
Failed to set limit: Invalid argument

The maximum limit seems a little too high. What's going on?


Solution

  • from man setrlimit:

    setrlimit() now returns with errno set to EINVAL in places that historically succeeded. ... Use "rlim_cur = min(OPEN_MAX, rlim_max)".

    The OPEN_MAX is defined as 10240 in <sys/syslimits.h>

    So it failed to set rlimit_cur to 19456.