Advanced Programming in the Unix Environment, 2nd Edは、どこでも動作する次のコードを提供します。これは非常に賢いですが、プロセスの rlimitsもチェックしないのは少し残念だと思います。rlimits は、プロセスが使用できる開いているファイルの数をさらに制限できるからです。それはさておき、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()
は、ソースと共にヘッダーで提供されapue.h
ます -- ルーチンの置き換えを簡単にコーディングできるはずです。)