linux下定时器的使用

/**
 *定时器
 *author lwh
 *date 2014/4/2
 * gcc -g -std=c99 -D_GNU_SOURCE timer.c -o timer -lrt
 */

#include <stdio.h>
#include <signal.h>
#include <time.h>

#define CLOCKID CLOCK_REALTIME

void *kernelFunc(void *data)
{
    printf("kernelFunc data=%s\n", (char *)data);
}

struct middleStruc
{
    void *(*callFunc)(void *);
    char *name;
};

void timerFunc(union sigval v) 
{
    printf("call timerFunc......\n");
    struct middleStruc *t = (struct middleStruc *)(v.sival_ptr);
    t->callFunc(t->name);
}

int main(int argc, char **argv)
{
    printf("start......\n");

    char *timerName[3] = {"aa", "bb", "cc"};

    for(int i = 0; i < 3; i++){
        //创建定时器 
        struct tm srvTm ;
        time_t timenow = time(NULL);
        localtime_r(&timenow, &srvTm);

        timer_t * mainTimer = (timer_t *)malloc( sizeof (timer_t));
        struct itimerspec * itimeout = (struct itimerspec *)malloc( sizeof (struct itimerspec));
        struct sigevent * sigev = (struct sigevent *)malloc( sizeof (struct sigevent));
        struct middleStruc * ontime = (struct middleStruc *)malloc( sizeof (struct middleStruc));

        ontime->callFunc = kernelFunc;
        ontime->name = timerName[i];

        sigev->sigev_notify = SIGEV_THREAD;
        sigev->sigev_notify_function = timerFunc;
        sigev->sigev_value.sival_ptr = (void *)ontime;

        if(timer_create(CLOCK_REALTIME, sigev, mainTimer) == -1){
            printf("fail to timer_create\n");
        }
        
        itimeout->it_value.tv_sec = 10;
        itimeout->it_value.tv_nsec = 0;
        itimeout->it_interval.tv_sec = 1;
        itimeout->it_interval.tv_nsec = 0;
        timer_settime(*mainTimer, 0, itimeout, NULL);
    }

    printf("end......\n");
    
    while(1) {}
    return 0;
}


 

typedef struct sigevent
{
    sigval_t sigev_value;
    int sigev_signo;
    int sigev_notify;

    union
    {
   int _pad[__SIGEV_PAD_SIZE];

   /* When SIGEV_SIGNAL and SIGEV_THREAD_ID set, LWP ID of the
      thread to receive the signal.  */
   __pid_t _tid;

   struct
  {
      void (*_function) (sigval_t);   /* Function to start.  */
      void *_attribute;           /* Really pthread_attr_t.  */
    } _sigev_thread;
    } _sigev_un;
} sigevent_t;


 

linux下定时器的使用,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。