使用epoll主循环延迟执行
如何使用epoll
创建代码的延迟执行或超时事件? libevent 和 libev 都有这个功能,但我不知道如何使用 epoll 来做到这一点。
目前主循环如下所示:
epoll_ctl(epfd, EPOLL_CTL_ADD, client_sock_fd, &epev);
while(1) {
int nfds = epoll_wait(epfd, &epev, 1, 10);
if (nfds < 0) exit(EXIT_FAILURE);
if (nfds > 0) {
// If an event has been recieved
}
// Do this every 10ms
}
我很清楚,可以通过简单地添加已经过去的时间来实现此功能,但使用 epoll 似乎是一个更干净的解决方案。
How would I create a delayed execution of code or timeout events using epoll
? Both libevent and libev has the functionality but I can't figure out how to do this using epoll.
Currently the main loop looks like this:
epoll_ctl(epfd, EPOLL_CTL_ADD, client_sock_fd, &epev);
while(1) {
int nfds = epoll_wait(epfd, &epev, 1, 10);
if (nfds < 0) exit(EXIT_FAILURE);
if (nfds > 0) {
// If an event has been recieved
}
// Do this every 10ms
}
I am well aware that this functionality could be achieved by simply adding how much time has passed but using epoll seems like a cleaner solution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以创建 timerfd 并添加epoll_wait 的文件描述符
You can create timerfd and add the file descriptor to the epoll_wait
愚蠢的问题:为什么不明确地记录时间呢?我在多 TCP 客户端中执行此操作(用于发送心跳),并且循环基本上执行以下操作:
get_time_in_usec
可以使用gettimeofday
或rdtsc
来实现linux。青年MMVStupid question: why not just keep track of the time explicitly? I do this in a multi-TCP client (for sending heartbeats) and the loop essentially does:
get_time_in_usec
can be implemented usinggettimeofday
orrdtsc
in linux. YMMV