Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

52 UNIX Standardization and Implementations Chapter 2


#include <unistd.h>
for (i = 0; i < sysconf(_SC_OPEN_MAX); i++)
close(i);

Our best option in this case is just to close all descriptors up to some arbitrary
limit — say,256. Weshow this technique in Figure2.17. As with our pathname
example, this strategy is not guaranteed to work for all cases, but it’s the best we can do
without using a moreexotic approach.
#include "apue.h"
#include <errno.h>
#include <limits.h>
#ifdef OPEN_MAX
static long openmax = OPEN_MAX;
#else
static long openmax = 0;
#endif
/*
* If OPEN_MAX is indeterminate, this might be inadequate.
*/
#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);
}

Figure 2.17Determine the number of file descriptors

We might be tempted to callcloseuntil we get an error return, but the error return
fromclose(EBADF)doesn’t distinguish between an invalid descriptor and a descriptor
that wasn’t open. If we tried this technique and descriptor 9 was not open but
descriptor 10 was, we would stop on 9 and never close 10. The dup function
(Section 3.12) does return a specific error whenOPEN_MAXis exceeded, but duplicating
adescriptor a couple of hundred times is an extreme way to determine this value.
Some implementations will returnLONG_MAXfor limit values that areeffectively
unlimited. Such is the case with the Linux limit forATEXIT_MAX(see Figure2.15).This
isn’t a good idea, because it can cause programs to behave badly.
Free download pdf