Linux Files and the Event Poll Interface - Waiting for Events with Epoll (
Page 3 of 4 )
The system call epoll_wait() waits for events on the file descriptors associated with the given epoll instance:
#include <sys/epoll.h>
int epoll_wait (int epfd,
struct epoll_event *events,
int maxevents,
int timeout);
A call to epoll_wait() waits up to timeout
milliseconds for events on the files associ
ated with the epoll instance
epfd
. Upon success,
events
points to memory containing
epoll_event
structures describing each event, up to a maximum of
maxevents
events. The return value is the number of events, or
-1
on error, in which case
errno
is set to one of the following:
EBADF
epfd
is not a valid file descriptor.
EFAULT
The process does not have write access to the
memory pointed at by
events
.
EINTR
The system call was interrupted by a signal before it
could complete.
EINVAL
epfd
is not a valid epoll instance, or
maxevents
is
equal to or less than
0
.
If
timeout
is
0
, the call returns immediately, even if no events are available, in which case the call will return
0
. If the
timeout
is
-1
, the call will not return until an event is available.
When the call returns, the
events
field of the
epoll_event
structure describes the events that occurred. The
data
field contains whatever the user set it to before invocation of
epoll_ctl()
.
A full
epoll_wait()
example looks like this:
#define MAX_EVENTS 64
struct epoll_event *events
;
int nr_events, i, epfd;
events = malloc (sizeof (struct epoll_event) * MAX_EVENTS);
if (!events) {
perror ("malloc");
return 1;
}
nr_events = epoll_wait (epfd, events, MAX_EVENTS, -1);
if (nr_events < 0) {
perror ("epoll_wait");
free (events);
return 1;
}
for (i = 0; i < nr_events; i++) {
printf ("event=%ld on fd=%d\n",
events[i].events,
events[i].data.fd);
/*
* We now can, per events[i].events, operate on
* events[i].data.fd without blocking.
*/
}
free (events);
We will cover the functions
malloc()
and
free()
in Chapter 8.