Search code examples
cmultithreadingglibc

get_nprocs() and get_nprocs_conf() -- How to do error checking


I am using get_nproc() and get_nprocs_conf() top get number of online and all processor cores present in my machine.

How do I check for errors with these functions. Any specific error values? Do they even notify of errors ? not sure.

I would really like to check for error with the call as my program would depend on the returned values a lot.

FYI - As these functions are available from GNU library I prefer these over sysconf (_SC_NPROCESSORS_ONLN) and sysconf (_SC_NPROCESSORS_CONF) so basically I want to avoid including extra file

Also, I see that these are declared in -- sys/sysinfo.h but wasn't able to find the definition. Any idea on where can I get that ?


Solution

  • get_nprocs and get_nprocs_conf are GNU extensions which are not documented to return errors. These functions are very unlikely to fail because they parse interfaces provided by the kernel in /sys or /proc. Still, failures can happen, either due to a kernel misconfiguration, a bug in the parser, or (most likely) a lack of resources causing open() to fail. In that case, the current implementation of both functions returns 1 without setting an error flag.

    In other words, you are expected to use the return value as if the functions cannot fail. Since the fallback value returned in the unlikely case of error is fairly reasonable, doing just that does not seem like it will cause problems.