[Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 463
  • Last Modified:

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.
0
n1443160
Asked:
n1443160
1 Solution
 
PhilippeCommented:

n1443160,

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.

   Philippe
   
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);}
    else
      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)
        perror("reading");
      printf("read %c from %s \n", c, i==0?"stdin":argv[i]);
      fds[i].revents = 0;
      }
  }
}

0

Featured Post

Upgrade your Question Security!

Add Premium security features to your question to ensure its privacy or anonymity. Learn more about your ability to control Question Security today.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now