An example use of poll()

I would like to see how to use poll()?
e.g. Open a list of files from the command line, use
poll to read and write to screen.
Who is Participating?
PhilippeConnect With a Mentor Commented:


First a short note on poll and normal files:

Poll will only tell you if reading a file would block or not. Thus on a normal file it will always say that the file is readable.

The program below will open all the files on the command line plus stdin. It will then use poll to find out which ones are readable and read one character from each at a time. It will poll once per second. Note that if any of the files is a normal file
you will get read errors as soon as you reach the end of the file (see above).

Two simple test with the program:

1. run it without command line arguments and type in some text
   It will print out your text each time you type return and
    std-in becomes readable.

2. Assuming you are on a unix system. Create a named pipe (a fifo) using the command mkfifo myfifo. Then in one window do
a cat > myfifo and in another window run the program with myfifo as parameter. You can now type in each window and see the text
appear as soon as you hit return.

 Hope this answers your question, I'll be glad to answer further questions.

Here is the sample program:

#include <poll.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

#define MAX_FILES 32

main (int argc, char ** argv)
  int i;
  struct pollfd fds[MAX_FILES];
  char c;

  /* use only fifos and not normal files ! */

  for (i=1; i< argc; i++)
    if ((fds[i].fd = open(argv[i],O_RDONLY)) == -1)
      {perror(argv[i]); exit(0);}
      fds[i].events = POLLIN;

  /* add stdin to make it more interesting */

  fds[0].fd = 0; /* 0 is stdin */
  fds[0].events = POLLIN;

  while (1) {
    /* wait a second for data to read from files */
    if (poll(fds, (unsigned long) argc, 1000) < 0)
      perror ("poll");

    for (i=0; i< argc; i++)
      if (fds[i].revents) {
      if (read(fds[i].fd,&c,1) != 1)
      printf("read %c from %s \n", c, i==0?"stdin":argv[i]);
      fds[i].revents = 0;

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.