使用epoll主循环延迟执行

发布于 2024-11-29 21:00:43 字数 459 浏览 3 评论 0原文

如何使用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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

贱人配狗天长地久 2024-12-06 21:00:43

您可以创建 timerfd 并添加epoll_wait 的文件描述符

You can create timerfd and add the file descriptor to the epoll_wait

暮光沉寂 2024-12-06 21:00:43

愚蠢的问题:为什么不明确地记录时间呢?我在多 TCP 客户端中执行此操作(用于发送心跳),并且循环基本上执行以下操作:

uint64_t last = get_time_in_usec();
uint64_t event_interval = 10 * 1000;
while(1) {
    int nfds = epoll_wait(epfd, &epev, 1, 0); /* note that i set timeout = 0 */
    if (nfds <= 0) { /* do some cleanup logic, handle EAGAIN */
    if (nfds > 0) { /* If an event has been received */ }
    if(get_time_in_usec() >= last + event_interval) { ... }
}

get_time_in_usec 可以使用 gettimeofdayrdtsc 来实现linux。青年MMV

Stupid 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:

uint64_t last = get_time_in_usec();
uint64_t event_interval = 10 * 1000;
while(1) {
    int nfds = epoll_wait(epfd, &epev, 1, 0); /* note that i set timeout = 0 */
    if (nfds <= 0) { /* do some cleanup logic, handle EAGAIN */
    if (nfds > 0) { /* If an event has been received */ }
    if(get_time_in_usec() >= last + event_interval) { ... }
}

get_time_in_usec can be implemented using gettimeofday or rdtsc in linux. YMMV

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文