linux使用epoll机制实现timer

 

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

const int EPOLL_SIZE = 10;
int test_timer_main(int argc, const char *argv[])
{
    int tfd, epfd, nfds;
    struct epoll_event event;
    struct epoll_event events[EPOLL_SIZE];
    timer_t ts;
        
    //创建timerfd, CLOCK_REALTIME为绝对时间,TFD_NONBLOCK为非阻塞
    tfd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK);  
    if (tfd < 0)
    {
        printf("timerfd_create error!" );
        return -1;
    }   
    struct timespec startTime, intervalTime;
    startTime.tv_sec = 0;    
    startTime.tv_nsec = 1;                         //相当于立即到达超时时间
    intervalTime.tv_sec = 3;                       //首次超时后,每三秒超时一次
    intervalTime.tv_nsec = 0;
    struct itimerspec newValue;
    newValue.it_value = startTime;
    newValue.it_interval = intervalTime;
    //设置超时时间,且为相对时间
    if (timerfd_settime(tfd, 0, &newValue, NULL) < 0)
    {
        printf("timerfd_settime error!");
        return -1;
    }
    //用epoll来监听描述符
    epfd = epoll_create(EPOLL_SIZE);
    if (epfd < 0)
    {
        printf("epoll_create error!");
        return -1;
    }

    event.data.fd = tfd;
    event.events = EPOLLIN;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, tfd, &event) < 0)//增加epoll的描述符
    {
        printf("epoll_ctl error!");
        return -1;
    }
    
    uint64_t count = 0;
    while (1)
    {
        //非阻塞等待
        nfds = epoll_wait(epfd, events, EPOLL_SIZE, -1);
        if (nfds == 0)
        {
            continue;
        }
        //printf("evt happen,%d\n",nfds);
        for (int i = 0; i < nfds; i++)
        {
            if (events[i].events & EPOLLIN)
            {
                uint64_t data;
                read(events[i].data.fd, &data, sizeof(uint64_t));
                count += data;
                ts = time(NULL);
                printf("read: %d,timer count: %d,ts=%d\n" ,data,count,ts);
            }
        }
    }
    return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值