Unix 环境中的高级编程,第 2 版为我们提供了以下应该可以在任何地方工作的代码;虽然它非常聪明,但我认为有点不幸的是它并没有检查进程的 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
标题中提供 - 应该很容易为您的例程编写替代代码。)