美文网首页
epoll 结合定时器

epoll 结合定时器

作者: Jesson3264 | 来源:发表于2020-07-01 14:44 被阅读0次
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <net/if.h>
#include <sys/epoll.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/timerfd.h>

struct param {
    struct itimerspec its;
    int tfd;
};

int CreateTimer(struct itimerspec *timeValue, time_t interval)
{
    if (!timeValue)
    {
        return -1;
    }

    int timefd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
    if (timefd < 0)
    {
            return -1;
    }

    struct timespec nw;
    if (clock_gettime(CLOCK_MONOTONIC, &nw) != 0)
    {
        close(timefd);
        return -1;
    }

    timeValue->it_value.tv_sec = nw.tv_sec + interval;
    timeValue->it_value.tv_nsec = 0;
    timeValue->it_interval.tv_sec = interval;
    timeValue->it_interval.tv_nsec = 0;

    int ret = timerfd_settime(timefd, TFD_TIMER_ABSTIME, timeValue, NULL);
    if (ret < 0)
    {
        close(timefd);
        return -1;
    }

    return timefd;
}

int main()
{
    int i = 0;
    struct itimerspec timeValue;
    int timefd = CreateTimer(&timeValue, 1);

    struct param pm;
    pm.its = timeValue;
    pm.tfd = timefd;

    int epollfd = epoll_create(100);

    struct epoll_event tevent;
    tevent.data.ptr = &pm;
    tevent.events = EPOLLIN | EPOLLET;

    epoll_ctl(epollfd, EPOLL_CTL_ADD, pm.tfd, &tevent);

    while (1)
    {
        struct epoll_event tevents[10];
        int n = epoll_wait(epollfd, tevents, 10, 2000);
        if (n == 0)
        {
            printf("timeout.\n");
            continue;
        }
        for (i = 0; i < n; ++i)
        {
            struct param* pm = (struct param*)(tevents[i].data.ptr);
            if (timefd == pm->tfd)
            {
                printf("has timeer event.\n");
                epoll_ctl(epollfd, EPOLL_CTL_DEL, pm->tfd, NULL);

                struct epoll_event ev;
                ev.events = EPOLLIN | EPOLLET;
                pm->its.it_value.tv_sec = pm->its.it_value.tv_sec +
                                          pm->its.it_interval.tv_sec;
                ev.data.ptr = pm;

                timerfd_settime(pm->tfd, TFD_TIMER_ABSTIME, &(pm->its), NULL);

                epoll_ctl(epollfd, EPOLL_CTL_ADD, pm->tfd, &ev);
            }

        }
    }

    return 0;
}

相关文章

网友评论

      本文标题:epoll 结合定时器

      本文链接:https://www.haomeiwen.com/subject/boncqktx.html