我正在写一个基于epoll的简单服务器类.为了唤醒epoll_wait(),我决定使用eventfd.据说它更适合于简单的事件交流,对此我表示同意.因此,我创建了活动并对其进行监视:
_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().最终,这在几个调试会话中起作用.
这是我的解决方法:知道每次fd可供写入时EPOLLOUT都会触发一个事件,因此我将停止代码更改为
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)");
现在可以了,但是不应该这样.
我不认为这应该很困难.我做错了什么?
谢谢
解决方法:
为我工作.作为参考,下面是完整的C代码:它输出“ eventfd_write”,“ 1”和“ DING:1”.在Linux 2.6.35-30(通用#56-Ubuntu SMP)上进行了测试.
#include <stdio.h>
#include <errno.h>
#include <sys/epoll.h>
#include <sys/eventfd.h>
#include <pthread.h>
#include <stdlib.h>
int _epollfd, _eventfd;
int init()
{
_epollfd = epoll_create1(0);
if (_epollfd == -1) abort();
_eventfd = eventfd(0, EFD_NONBLOCK);
struct epoll_event evnt = {0};
evnt.data.fd = _eventfd;
evnt.events = EPOLLIN | EPOLLET;
if (epoll_ctl(_epollfd, EPOLL_CTL_ADD, _eventfd, &evnt) == -1)
abort();
}
void *subprocess(void *arg)
{
static const int EVENTS = 20;
struct epoll_event evnts[EVENTS];
while (1) {
int count = epoll_wait(_epollfd, evnts, EVENTS, -1);
printf("%d\n", count);
if (count == -1)
{
if (errno != EINTR)
{
perror("epoll_wait");
return NULL;
}
}
int i;
for (i = 0; i < count; ++i)
{
struct epoll_event *e = evnts + i;
if (e->data.fd == _eventfd)
{
eventfd_t val;
eventfd_read(_eventfd, &val);
printf("DING: %lld\n", (long long)val);
return NULL;
}
}
}
}
int main()
{
pthread_t th;
init();
if (pthread_create(&th, NULL, subprocess, NULL) != 0)
abort();
sleep(2);
printf("eventfd_write\n");
eventfd_write(_eventfd, 1);
sleep(2);
}