The Linux Programming Interface

(nextflipdebug5) #1

1336 Chapter 63


for (fd = 0; fd < nfds; fd++)
printf("%d: %s%s\n", fd, FD_ISSET(fd, &readfds)? "r" : "",
FD_ISSET(fd, &writefds)? "w" : "");

if (pto != NULL)
printf("timeout after select(): %ld.%03ld\n",
(long) timeout.tv_sec, (long) timeout.tv_usec / 10000);
exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––––––––––– altio/t_select.c
In the following shell session log, we demonstrate the use of the program in List-
ing 63-1. In the first example, we make a request to monitor file descriptor 0 for
input with a 10-second timeout:

$ ./t_select 10 0r
Press Enter, so that a line of input is available on file descriptor 0
ready = 1
0: r
timeout after select(): 8.003
$ Next shell prompt is displayed

The above output shows us that select() determined that one file descriptor was
ready. This was file descriptor 0, which was ready for reading. We can also see that
the timeout was modified. The final line of output, consisting of just the shell $
prompt, appeared because the t_select program didn’t read the newline character
that made file descriptor 0 ready, and so that character was read by the shell, which
responded by printing another prompt.
In the next example, we again monitor file descriptor 0 for input, but this time
with a timeout of 0 seconds:

$ ./t_select 0 0r
ready = 0
timeout after select(): 0.000

The select() call returned immediately, and found no file descriptor was ready.
In the next example, we monitor two file descriptors: descriptor 0, to see if
input is available, and descriptor 1, to see if output is possible. In this case, we specify
the timeout as NULL (the first command-line argument is a hyphen), meaning infinity:

$ ./t_select - 0r 1w
ready = 1
0:
1: w

The select() call returned immediately, informing us that output was possible on file
descriptor 1.
Free download pdf