我正在写一个基于epoll的简单服务器类。为了唤醒epoll_wait()
,我决定使用eventfd。据说它更适合简单的事件沟通,我同意这一点。所以,我建立了我的情况下,把手表就可以了:linux - 无法让eventfd一起使用epoll
_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)");
在消息等待循环后,在一个单独的线程:
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;
}
}
,当然,也停止服务器是代码:
eventfd_write(_eventfd, 1);
对于我无法解释原因,我无法仅仅通过书面形式向事件唤醒epoll_wait()
。最终,这在几个调试会话中起作用。
这里是我的解决办法:知道EPOLLOUT
会在每次fd是可用于写入时间触发一个事件,我改变了停止码的
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)");
现在,它的工作原理,但它不应该是这个样子。
我不认为这应该是困难的。我做错了什么?
谢谢
什么是'_events'初始化为? – caf 2011-03-19 01:51:29
_events被设置为EPOLLIN | EPOLLET – user666412 2011-10-14 15:45:39