I am writing a simple server class based on epoll. To wake up epoll_wait(), I decided to use eventfd. They say that it is better suited for a simple exchange of events, and I agree with that. So I created my event and looked at 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 in 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 stopped the server:
eventfd_write(_eventfd, 1);
For reasons that I cannot explain, I could not wake up epoll_wait()by simply recording this event. In the end, it worked in several debugging sessions.
Here is my workaround: knowing what the EPOLLOUTevent will trigger every time fd is writable, 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 should not be so.
, . ?