How do I use poll()?

How do I use poll()?


poll() accepts a pointer to a list of struct pollfd, in
which the descriptors and the events you wish to poll for are stored.
The events are specified via a bitwise mask in the events field of the
structure. The instance of the structure will later be filled in and
returned to you with any events which occured. Macros defined by
`poll.h' on SVR4 (probably older versions as well), are used to
specify the events in the field. A timeout may be specified in
milliseconds, only the type provided is an integer which is quite
perplexing. A timeout of 0 causes poll() to return immediately;
a value of @math{-1} will suspend poll until an event is found to be
true.




struct pollfd {
int fd; /* The descriptor. */
short events; /* The event(s) is/are specified here. */
short revents; /* Events found are returned here. */
};



A lot like select(), the return value if positive reflects how
many descriptors were found to satisfy the events requested. A zero
return value is returned if the timeout period is reached before any of
the events specified have occured. A negative value should immediately
be followed by a check of errno, since it signifies an error.



If no events are found, revents is cleared, so there's no need
for you to do this yourself.



The returned events are tested to contain the event.



Here's an example:




/* Poll on two descriptors for Normal data, or High priority data.
If any found call function handle() with appropriate descriptor
and priority. Don't timeout, only give up if error, or one of the
descriptors hangs up. */

#include <stdlib.h>
#include <stdio.h>

#include <sys/types.h>
#include <stropts.h>
#include <poll.h>

#include <unistd.h>
#include <errno.h>
#include <string.h>

#define NORMAL_DATA 1
#define HIPRI_DATA 2

int poll_two_normal(int fd1,int fd2)
{
struct pollfd poll_list[2];
int retval;

poll_list[0].fd = fd1;
poll_list[1].fd = fd2;
poll_list[0].events = POLLIN|POLLPRI;
poll_list[1].events = POLLIN|POLLPRI;

while(1)
{
retval = poll(poll_list,(unsigned long)2,-1);
/* Retval will always be greater than 0 or -1 in this case.
Since we're doing it while blocking */

if(retval < 0)
{
fprintf(stderr,"Error while polling: %s\n",strerror(errno));
return -1;
}

if(((poll_list[0].revents&POLLHUP) == POLLHUP) ||
((poll_list[0].revents&POLLERR) == POLLERR) ||
((poll_list[0].revents&POLLNVAL) == POLLNVAL) ||
((poll_list[1].revents&POLLHUP) == POLLHUP) ||
((poll_list[1].revents&POLLERR) == POLLERR) ||
((poll_list[1].revents&POLLNVAL) == POLLNVAL))
return 0;

if((poll_list[0].revents&POLLIN) == POLLIN)
handle(poll_list[0].fd,NORMAL_DATA);
if((poll_list[0].revents&POLLPRI) == POLLPRI)
handle(poll_list[0].fd,HIPRI_DATA);
if((poll_list[1].revents&POLLIN) == POLLIN)
handle(poll_list[1].fd,NORMAL_DATA);
if((poll_list[1].revents&POLLPRI) == POLLPRI)
handle(poll_list[1].fd,HIPRI_DATA);
}
}






Home FAQ