The following code creates an epoll file descriptor:
int epollfd; epollfd = epoll_create(5); /* We'll (probably) monitor 5 fds */
We then repeatedly perform the following steps to add each file descriptor to the interest list.
struct epoll_event ev; ev.data.fd = fd; /* Returned via later epoll_wait() */ ev.events = EPOLLIN; /* Monitor for input */ epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, ev);
Now we can wait for file descriptors in the interest list to become ready:
#define MAX_EVENTS 5 /* Max. items to return from ready list in a single epoll_wait() */ struct epoll_event evlist[MAX_EVENTS] ready = epoll_wait(epollfd, evlist, MAX_EVENTS, -1); for (j = 0; j < ready; j++) { if (evlist[j].events & EPOLLIN) { s = read(evlist[j].data.fd, buf, MAX_BUF); printf(" read %d bytes: %.*s\n", s, s, buf); } if (evlist[j].events & (EPOLLHUP | EPOLLERR)) close(evlist[j].data.fd); /* End-of-file or error */ }
Notice that the number of the ready file descriptor was obtained via evlist[j].data.fd.
(C) 2006, Michael Kerrisk