Alternative I/O Models 1341
srandom((int) time(NULL));
for (j = 0; j < numWrites; j++) {
randPipe = random() % numPipes;
printf("Writing to fd: %3d (read fd: %3d)\n",
pfds[randPipe][1], pfds[randPipe][0]);
if (write(pfds[randPipe][1], "a", 1) == -1)
errExit("write %d", pfds[randPipe][1]);
}
/* Build the file descriptor list to be supplied to poll(). This list
is set to contain the file descriptors for the read ends of all of
the pipes. */
for (j = 0; j < numPipes; j++) {
pollFd[j].fd = pfds[j][0];
pollFd[j].events = POLLIN;
}
ready = poll(pollFd, numPipes, -1); /* Nonblocking */
if (ready == -1)
errExit("poll");
printf("poll() returned: %d\n", ready);
/* Check which pipes have data available for reading */
for (j = 0; j < numPipes; j++)
if (pollFd[j].revents & POLLIN)
printf("Readable: %d %3d\n", j, pollFd[j].fd);
exit(EXIT_SUCCESS);
}
––––––––––––––––––––––––––––––––––––––––––––––––––––––– altio/poll_pipes.c
63.2.3 When Is a File Descriptor Ready?
Correctly using select() and poll() requires an understanding of the conditions
under which a file descriptor indicates as being ready. SUSv3 says that a file
descriptor (with O_NONBLOCK clear) is considered to be ready if a call to an I/O func-
tion would not block, regardless of whether the function would actually transfer data.
The key point is italicized: select() and poll() tell us whether an I/O operation would
not block, rather than whether it would successfully transfer data. In this light, let
us consider how these system calls operate for different types of file descriptors.
We show this information in tables containing two columns:
z The select() column indicates whether a file descriptor is marked as readable (r),
writable (w), or having an exceptional condition (x).
z The poll() column indicates the bit(s) returned in the revents field. In these
tables, we omit mention of POLLRDNORM, POLLWRNORM, POLLRDBAND, and POLLWRBAND.
Although some of these flags may be returned in revents in various circum-
stances (if they are specified in events), they convey no useful information
beyond that provided by POLLIN, POLLOUT, POLLHUP, and POLLERR.