1340 Chapter 63
The following shell session shows an example of what we see when running this
program. The command-line arguments to the program specify that ten pipes
should be created, and writes should be made to three randomly selected pipes.
$ ./poll_pipes 10 3
Writing to fd: 4 (read fd: 3)
Writing to fd: 14 (read fd: 13)
Writing to fd: 14 (read fd: 13)
poll() returned: 2
Readable: 3
Readable: 13
From the above output, we can see that poll() found two pipes had data available
for reading.
Listing 63-2: Using poll() to monitor multiple file descriptors
––––––––––––––––––––––––––––––––––––––––––––––––––––––– altio/poll_pipes.c
#include <time.h>
#include <poll.h>
#include "tlpi_hdr.h"
int
main(int argc, char *argv[])
{
int numPipes, j, ready, randPipe, numWrites;
int (*pfds)[2]; /* File descriptors for all pipes */
struct pollfd *pollFd;
if (argc < 2 || strcmp(argv[1], "--help") == 0)
usageErr("%s num-pipes [num-writes]\n", argv[0]);
/* Allocate the arrays that we use. The arrays are sized according
to the number of pipes specified on command line */
numPipes = getInt(argv[1], GN_GT_0, "num-pipes");
pfds = calloc(numPipes, sizeof(int [2]));
if (pfds == NULL)
errExit("malloc");
pollFd = calloc(numPipes, sizeof(struct pollfd));
if (pollFd == NULL)
errExit("malloc");
/* Create the number of pipes specified on command line */
for (j = 0; j < numPipes; j++)
if (pipe(pfds[j]) == -1)
errExit("pipe %d", j);
/* Perform specified number of writes to random pipes */
numWrites = (argc > 2)? getInt(argv[2], GN_GT_0, "num-writes") : 1;