我是 libev 的新手,我很难理解它。我之前使用过 select()、poll() 和 epoll(),它们很容易理解和实现。我现在想从 epoll 切换到 libev。这是我目前正在使用 epoll 做的事情 -
short int state[10000]; // stores the events for all fd
state[fd] |= current_state // Update state for the fd, current_state could be either EPOLLIN or EPOLLOUT but not both
/* attempt to add fd to epoll for monitoring. If fd already exists, then just modify the events */
ev.events = state[fd];
ev.data.fd = fd;
epollctl = epoll_ctl(epollfd, EPOLL_CTL_ADD, fd, &ev);
if(epollctl == -1 && errno == EEXIST)
epollctl = epoll_ctl(epollfd, EPOLL_CTL_MOD, fd, &ev);
while(1)
{
num = epoll_wait (epollfd, events, 100000 , -1);
for(i = 0, i < num, ++i)
{
/* process the read and tell epoll to not notify anymore read events for given fd */
if(events[i].events & EPOLLIN)
{
process_read (m, m->read, events[i].data.fd );
state[events[i].data.fd] &= ~(EPOLLIN)
ev.events = state[events[i].data.fd]
ev.data.fd = events[i].data.fd;
epollctl = epoll_ctl(epollfd, EPOLL_CTL_MOD, events[i].data.fd, &ev);
}
/* process the write and tell epoll to not notify anymore write events for given fd */
if(events[i].events & EPOLLOUT)
{
process_write (m, m->write, events[i].data.fd );
state[events[i].data.fd] &= ~(EPOLLOUT)
ev.events = state[events[i].data.fd]
ev.data.fd = events[i].data.fd;
epollctl = epoll_ctl(epollfd, EPOLL_CTL_MOD, events[i].data.fd, &ev);
}
/* remove fd from epoll on error */
if(events[i].events & EPOLLERR)
epollctl = epoll_ctl(epollfd, EPOLL_CTL_DEL, events[i].data.fd, &ev);
}
}
这不是完整的代码,在此处发布时故意省略了错误检查和其他不相关的内容,因此您可以简单地专注于逻辑。我正在寻找 libev 等效方法来实现以下目标 -
- 添加fd进行监控
- 从监控中删除 fd
- 修改已被监视的 fd 的事件(读/写)。
有人可以为我提供上述 epoll 代码的粗略 libev 等效模板,将不胜感激。