Reputation: 33445
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)?
Upvotes: 2
Views: 1959
Reputation: 104080
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.)
Upvotes: 5
Reputation: 97835
See getdtablesize
. It has a conformance note:
SVr4, 4.4BSD (the getdtablesize() function first appeared in 4.2BSD). It is not specified in POSIX.1-2001; portable applications should employ sysconf(_SC_OPEN_MAX) instead of this call.
Upvotes: 2