Linux epoll版定時器


#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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM