Avoiding Retardation With Epoll

So epoll is cool. Say you’ve written this cool piece of code that does

epoll_ctl(efd, EPOLL_CTL_ADD, fd, {EPOLLIN | EPOLLRDHUP | EPOLLET, fd})

on everything you care about and then you write another cool bit of code that does

epoll_event ev;
epoll_wait(efd, &ev, 1, -1);

int fd = ev.data.fd;
int trigger = ev.events;

if (trigger & EPOLLRDHUP) {
  printf("remote %d closed their connection\n", fd);
  close(fd);
} else if (trigger & EPOLLIN) {
  printf("got data from %d\n", fd);
  // stuff
}

So then you write a test client which can send and disconnect and everything works so your code must be legendary right? Wrong. What if you opened a connection just to send a stream of bytes to just immediately close? If this happens fast enough, epoll will agregate the events into a single event where trigger & EPOLLIN && trigger & EPOLLRDHUP == true, and we only process the disconnect. So save yourself the trouble, process EPOLLRDHUP at the end and don’t use if else unless you only want to process events partially.

This entry was posted in Software. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *