timerfd epoll

#include <sys/timerfd.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <stdio.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>

#define MAX_EVENTS 5
#define EPOLL_TIMEOUT_MS 5000  // epoll wait timeout in milliseconds

int main() {
    int tfd, epoll_fd;
    struct epoll_event events[MAX_EVENTS];
    struct itimerspec ts;
    uint64_t expirations;
    ssize_t s;

    // Create a timerfd
    tfd = timerfd_create(CLOCK_MONOTONIC, 0);
    if (tfd == -1) {
        perror("timerfd_create");
        return 1;
    }

    // Set the timer to expire every 1 seconds, starting from 1 second
    ts.it_interval.tv_sec = 1;
    ts.it_interval.tv_nsec = 0;
    ts.it_value.tv_sec = 1;
    ts.it_value.tv_nsec = 0;

    if (timerfd_settime(tfd, 0, &ts, NULL) == -1) {
        perror("timerfd_settime");
        close(tfd);
        return 1;
    }

    // Create epoll instance
    epoll_fd = epoll_create1(0);
    if (epoll_fd == -1) {
        perror("epoll_create1");
        close(tfd);
        return 1;
    }

    // Add tfd to epoll events
    struct epoll_event event;
    event.events = EPOLLIN;  // Read events
    event.data.fd = tfd;
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, tfd, &event) == -1) {
        perror("epoll_ctl");
        close(epoll_fd);
        close(tfd);
        return 1;
    }

    // Wait for events
    while (1) {
        int num_events = epoll_wait(epoll_fd, events, MAX_EVENTS, EPOLL_TIMEOUT_MS);
        if (num_events == -1) {
            perror("epoll_wait");
            break;
        } else if (num_events == 0) {
            printf("Timeout occurred in epoll_wait\n");
            continue;
        }

        for (int i = 0; i < num_events; i++) {
            if (events[i].data.fd == tfd) {
                // Read the number of expirations
                s = read(tfd, &expirations, sizeof(uint64_t));
                if (s != sizeof(uint64_t)) {
                    perror("read");
                    break;
                }
                printf("Timer expired %llu times\n", (unsigned long long)expirations);
            }
        }

        sleep(3);
    }

    // Cleanup
    close(epoll_fd);
    close(tfd);

    return 0;
}

  • 4
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值