Linux epoll版定时器

Stella981
• 阅读 775
#ifndef __MYTIMER_H_
#define __MYTIMER_H_

/***************
高并发场景下的定时器
*****************/

//定时器回调函数
typedef void *(*TimerCallback)(int fd, void *);

typedef enum enFD_TYPE
{
    FD_TIMER,
    FD_SOCKET,
    FD_FILE,
}ENFD_TYPE;

struct STEpollParam
{
    int fd;                  //文件描述符
    ENFD_TYPE enType;        //文件描述符类型
    TimerCallback cb;        //定时器回调函数
    void * pvParam;          //回调函数参数
};

//创建定时器对象
int createTimer(unsigned int uiSec, unsigned int uiNsec);

//设置文件描述符非阻塞
int setNoBlock(int fd);

//创建epoll
int createEpoll();

//添加文件描述符到epoll
int addFdToEpoll(int epfd, STEpollParam *pstParam);

//消息处理
int recvMsg(void *pvParam);

//等待消息
void epollWait(int epfd);

#endif

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

#include "comontype.h"
#include "mytimer.h"

#define EPOOL_SIZE 32000
#define EPOOL_EVENT 32


/********************************************************
   Func Name: createTimer
Date Created: 2018-7-30
 Description: 创建定时器对象
       Input: uiTvSec:设置间隔多少秒
             uiTvUsec:设置间隔多少微秒
      Output: 
      Return: 文件句柄
     Caution: 
*********************************************************/
int createTimer(unsigned int uiSec, unsigned int uiNsec)
{
    int iRet = 0;
    int tfd = 0;
    struct itimerspec timeValue;

    //初始化定时器
    /*
     When the file descriptor is no longer required it should be closed.  
     When all file descriptors associated with the same timer object have been closed, 
     the timer is disarmed and its resources are freed by the kernel.

     意思是该文件句柄还是需要调用close函数关闭的
    */
    tfd = timerfd_create(CLOCK_REALTIME,0);
    if (tfd < 0)
    {
        return -1;
    }

    //设置开启定时器
    /*
    Setting either field of new_value.it_value to a nonzero value arms the timer. 
    Setting both fields of new_value.it_value to zero disarms the timer.
    意思是如果不设置it_interval的值非零,那么即关闭定时器
    */
    timeValue.it_value.tv_sec = 1;
    timeValue.it_value.tv_nsec = 0;

    //设置定时器周期
    timeValue.it_interval.tv_sec = (time_t)uiSec;
    timeValue.it_interval.tv_nsec = (long)uiNsec;

    iRet = timerfd_settime(tfd, 0, &timeValue, NULL);
    if (iRet < 0)
    {
        return -1;
    }

    return tfd;
}

/********************************************************
   Func Name: setNoBlock
Date Created: 2018-7-27
 Description: 设置文件描述符非阻塞
       Input: fd:文件描述符
      Output:         
      Return: error code
     Caution: 
*********************************************************/
int setNoBlock(IN int fd)
{
    int iRet = DEFAULT_ERROR;

    int iOption = -1;

    iOption = fcntl(fd, F_GETFD);
    if(iOption < 0)
    {
        iRet = DEFAULT_ERROR;
        return iRet;
    }

    iOption = iOption | O_NONBLOCK;

    iOption = fcntl(fd,F_SETFD,iOption);
    if(iOption < 0)
    {
        iRet = DEFAULT_ERROR;
        return iRet;
    }

    return RESULT_OK;
}

/********************************************************
   Func Name: createEpoll
Date Created: 2018-7-30
 Description: 创建epoll
       Input: 
      Output:         
      Return: epoll句柄
     Caution: 
*********************************************************/
int createEpoll()
{
    int epfd = 0;

    /*
    When no longer required,
    the file descriptor returned by epoll_create() should be closed byusing close(2).  
    When all file descriptors referring to an epoll instance have been closed, 
    the kernel destroys the instance and releases the associated resources for reuse.

    意思是用完需要调用close函数关闭epoll句柄
    */
    epfd = epoll_create(EPOOL_SIZE);
    if (epfd < 0)
    {
        return -1;
    }

    return epfd;
}

/********************************************************
   Func Name: addFdToEpoll
Date Created: 2018-7-30
 Description: 添加文件描述符到epoll
       Input: 
      Output:         
      Return: error code
     Caution: 
*********************************************************/
int addFdToEpoll(int epfd, STEpollParam *pstParam)
{
    int iRet = DEFAULT_ERROR;
    struct epoll_event ev;
    ev.data.ptr = pstParam;
    ev.events = EPOLLIN | EPOLLERR | EPOLLHUP;
    iRet = epoll_ctl(epfd, EPOLL_CTL_ADD, pstParam->fd, &ev);
    if (iRet < 0)
    {
        return DEFAULT_ERROR;
    }
    return RESULT_OK;
}

/********************************************************
   Func Name: recvMsg
Date Created: 2018-7-30
 Description: 消息处理
       Input: pvParam:参数指针
      Output:         
      Return: 
     Caution: 
*********************************************************/
int recvMsg(void *pvParam)
{
    int iRet = DEFAULT_ERROR;
    STEpollParam * pstParam = NULL;

    if (NULL == pvParam)
    {
        iRet = PARAM_ERROR;
        return iRet;
    }
    pstParam = (STEpollParam *)pvParam;
    switch(pstParam->enType)
    {
    case FD_TIMER:
        pstParam->cb(pstParam->fd, pstParam->pvParam);
        break;
    default:
        break;
    }
    return RESULT_OK;
}

/********************************************************
   Func Name: epollWait
Date Created: 2018-7-30
 Description: 等待消息
       Input: epfd:epoll句柄
      Output:         
      Return: 
     Caution: 
*********************************************************/
void epollWait(int epfd)
{
    int i = 0;
    int nfds = 0;
    struct epoll_event *events = NULL;

    //分配epoll事件内存
    events = (struct epoll_event *)malloc(sizeof(struct epoll_event)*EPOOL_EVENT);
    if (NULL == events)
    {
        return ;
    }
    memset(events, 0, sizeof(struct epoll_event)*EPOOL_EVENT);

    for (;;)
    {
        nfds = epoll_wait(epfd, events, EPOOL_EVENT, -1);
        if (nfds < 0)
        {
            break;
        }
        for (i = 0; i < nfds; i++ )
        {
            //监听读事件
            if (events[i].events & EPOLLIN)
            {
                recvMsg(events[i].data.ptr);
            }
        }
    }

    //关闭epoll
    close(epfd);

    return ;
}

#include <iostream>

using namespace std;

#include "mytimer.h"

//#include <sys/timerfd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include "comontype.h"

#define INTERVAL 3

void * timerFunc(int fd, void *pvParam)
{
    long data = 0;
    int *p = NULL;

    p = (int *)pvParam;
    read(fd, &data, sizeof(long));
    printf("data = %lu and p = %d \n", data, *p);

    return NULL;
}

int test()
{
    STEpollParam *pstParam =new STEpollParam;
    int tfd = 0;
    int num = 10;

    //初始化epoll
    int epfd = createEpoll();
    if (epfd < 0)
    {
        cout << "createEpoll() failed ." << endl;
        return -1;
    }
    //初始化定时器
    tfd = createTimer(INTERVAL,0);
    if (tfd < 0)
    {
        cout << "createTimer() failed ." << endl;
        return -1;
    }

    pstParam->fd = tfd;
    pstParam->enType = FD_TIMER;
    pstParam->cb = timerFunc;
    pstParam->pvParam = &num;

    addFdToEpoll(epfd, pstParam);

    epollWait(epfd);

    //关闭定时器文件描述符
    close(tfd);

    DE_FREE(pstParam);

    return 0;
}

int main()
{
    test();
    getchar();
    return 0;
}
点赞
收藏
评论区
推荐文章
blmius blmius
3年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Easter79 Easter79
3年前
swap空间的增减方法
(1)增大swap空间去激活swap交换区:swapoff v /dev/vg00/lvswap扩展交换lv:lvextend L 10G /dev/vg00/lvswap重新生成swap交换区:mkswap /dev/vg00/lvswap激活新生成的交换区:swapon v /dev/vg00/lvswap
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Jacquelyn38 Jacquelyn38
3年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
Wesley13 Wesley13
3年前
Java获得今日零时零分零秒的时间(Date型)
publicDatezeroTime()throwsParseException{    DatetimenewDate();    SimpleDateFormatsimpnewSimpleDateFormat("yyyyMMdd00:00:00");    SimpleDateFormatsimp2newS
Stella981 Stella981
3年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Wesley13 Wesley13
3年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
3年前
00:Java简单了解
浅谈Java之概述Java是SUN(StanfordUniversityNetwork),斯坦福大学网络公司)1995年推出的一门高级编程语言。Java是一种面向Internet的编程语言。随着Java技术在web方面的不断成熟,已经成为Web应用程序的首选开发语言。Java是简单易学,完全面向对象,安全可靠,与平台无关的编程语言。
Stella981 Stella981
3年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
3年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
10个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这