【epoll和timer结合,实现定时调用】

1.废话不多说,直接上源码

需要包含的头文件

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

#include <stdint.h>
#include <stdlib.h>

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>  //open 头文件

#include <unistd.h>  //close 头文件

2.定义epoll描述符epollfd,timer描述符timerfd

#define EPOLL_LISTEN_CNT 256
#define EPOLL_LISTEN_TIMEOUT 500
static int g_epollfd = -1;
static int g_timerfd = -1;

static int epoll_add_fd(int fd){
    int ret;
    struct epoll_event event;

    memset(&event, 0, sizeof(event));
    event.data.fd = fd;
    event.events = EPOLLIN | EPOLLET;

    ret = epoll_ctl(g_epollfd, EPOLL_CTL_ADD, fd, &event);
    if (ret < 0){
        return -1;
    }

    return 0;
}

static int epollfd_init(){
    int epfd;

    /* create epoll fd */
    epfd = epoll_create(EPOLL_LISTEN_CNT);
    if (epfd < 0){
        return -1;
    }
    g_epollfd = epfd;

    return epfd;
}

static int timerfd_init()
{
    int tmfd;
    int ret;
    struct itimerspec new_value;

    new_value.it_value.tv_sec = 0;
    new_value.it_value.tv_nsec = 10 * 1000 * 1000;
    new_value.it_interval.tv_sec = 0;
    new_value.it_interval.tv_nsec = 10 * 1000 * 1000;

    /* create timer fd */
    tmfd = timerfd_create(CLOCK_MONOTONIC, 0);
    if (tmfd < 0){
        return -1;
    }

    ret = timerfd_settime(tmfd, 0, &new_value, NULL);
    if (ret < 0){
        close(tmfd);
        return -1;
    }

    if (epoll_add_fd(tmfd)){
        close(tmfd);
        return -1;
    }
    g_timerfd = tmfd;

    return 0;
}

3.两个用于,定义打印函数

void print_some_char(){
    printf("hello world\n");
}

void print_timer_char(){
    printf("this is timer\n");
}

4.main函数

int main(){

    epollfd_init();
    timerfd_init();

    int i = 0;
    int fd_cnt = 0;
    int sfd;
    struct epoll_event events[EPOLL_LISTEN_CNT];
    int count = 0;
    memset(events, 0, sizeof(events));

    while(1) {
        /* wait epoll event */
        fd_cnt = epoll_wait(g_epollfd, events, EPOLL_LISTEN_CNT, EPOLL_LISTEN_TIMEOUT);
        for (i = 0; i < fd_cnt; i++){
            sfd = events[i].data.fd;

            if (!(events[i].events & EPOLLIN)){
                continue;
            }

            if (sfd != g_timerfd){
                continue;
            }

            uint64_t exp;
            read(sfd, &exp, sizeof(uint64_t));

            //每次进来10ms,限制20ms一次
            if ((count++) % 2 != 0){
                continue;
            }

            print_timer_char();
            print_some_char();
        }
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值