1334 Chapter 63
If we use the Linux-specific personality() system call to set a personality that
includes the STICKY_TIMEOUTS personality bit, then select() doesn’t modify the
structure pointed to by timeout.
Return value from select()
As its function result, select() returns one of the following:
z A return value of –1 indicates that an error occurred. Possible errors include
EBADF and EINTR. EBADF indicates that one of the file descriptors in readfds, writefds,
or exceptfds is invalid (e.g., not currently open). EINTR, indicates that the call was
interrupted by a signal handler. (As noted in Section 21.5, select() is never auto-
matically restarted if interrupted by a signal handler.)
z A return value of 0 means that the call timed out before any file descriptor became
ready. In this case, each of the returned file descriptor sets will be empty.
z A positive return value indicates that one or more file descriptors is ready. The
return value is the number of ready descriptors. In this case, each of the
returned file descriptor sets must be examined (using FD_ISSET()) in order to
find out which I/O events occurred. If the same file descriptor is specified in
more than one of readfds, writefds, and exceptfds, it is counted multiple times if it
is ready for more than one event. In other words, select() returns the total num-
ber of file descriptors marked as ready in all three returned sets.
Example program
The program in Listing 63-1 demonstrates the use of select(). Using command-line
arguments, we can specify the timeout and the file descriptors that we wish to moni-
tor. The first command-line argument specifies the timeout for select(), in seconds. If
a hyphen (-) is specified here, then select() is called with a timeout of NULL, meaning
block indefinitely. Each of the remaining command-line arguments specifies the
number of a file descriptor to be monitored, followed by letters indicating the opera-
tions for which the descriptor is to be checked. The letters we can specify here are
r(ready for read) and w (ready for write).
Listing 63-1: Using select() to monitor multiple file descriptors
––––––––––––––––––––––––––––––––––––––––––––––––––––––––– altio/t_select.c
#include <sys/time.h>
#include <sys/select.h>
#include "tlpi_hdr.h"
static void
usageError(const char *progName)
{
fprintf(stderr, "Usage: %s {timeout|-} fd-num[rw]...\n", progName);
fprintf(stderr, " - means infinite timeout; \n");
fprintf(stderr, " r = monitor for read\n");
fprintf(stderr, " w = monitor for write\n\n");
fprintf(stderr, " e.g.: %s - 0rw 1w\n", progName);
exit(EXIT_FAILURE);
}