I'm writing a simple server class based on epoll. In order to wake up epoll_wait()
, I decided to use an eventfd. It is said that it is better suited for simple event communication and I agree with that. So I created my event and put a watch on it:
_epollfd = epoll_create1(0);
if (_epollfd == -1) throw ServerError("epoll_create");
_eventfd = eventfd(0, EFD_NONBLOCK);
epoll_event evnt = {0};
evnt.data.fd = _eventfd;
evnt.events = _events;
if (epoll_ctl(_epollfd, EPOLL_CTL_ADD, _eventfd, &evnt) == -1)
throw ServerError("epoll_ctl(add)");
later in the message waiting loop, on a separate thread:
int count = epoll_wait(_epollfd, evnts, EVENTS, -1);
if (count == -1)
{
if (errno != EINTR)
{
perror("epoll_wait");
return;
}
}
for (int i = 0; i < count; ++i)
{
epoll_event & e = evnts[i];
if (e.data.fd == _serverSock)
connectionAccepted();
else if (e.data.fd == _eventfd)
{
eventfd_t val;
eventfd_read(_eventfd, &val);
return;
}
}
and, of course, the code that stop the server was:
eventfd_write(_eventfd, 1);
For reasons that I can't explain, I was unable to wake up the epoll_wait()
just by writing to the event. Eventually, this worked in a few debugging sessions.
Here is my workaround: knowing that EPOLLOUT
will trigger an event every time the fd is available for writing, I changed the stop code to
epoll_event evnt = {0};
evnt.data.fd = _eventfd;
evnt.events = EPOLLOUT;
if (epoll_ctl(_epollfd, EPOLL_CTL_MOD, _eventfd, &evnt) == -1)
throw ServerError("epoll_ctl(mod)");
Now it works but It shouldn't be this way.
I don't believe this should be any difficult. What have I done wrong?
Thanks