프로그래밍/Unix/Linux

리눅스에서 여러개의 타이머 구현 샘플

AlwaysNR 2015. 7. 30. 13:36


#include <cstdio>

#include <cstdlib>

#include <cstring>

#include <sys/time.h>

#include <unistd.h>

#include <signal.h>

#include <time.h>


timer_t firstTimerID;

timer_t secondTimerID;

timer_t thirdTimerID;


static void timerHandler( int sig, siginfo_t *si, void *uc )

{

    timer_t *tidp;


    tidp = (void**)(si->si_value.sival_ptr);


    if ( *tidp == firstTimerID )

        printf("2ms\n");

    else if ( *tidp == secondTimerID )

        printf("10ms\n");

    else if ( *tidp == thirdTimerID )

        printf("100ms\n");

}


static int makeTimer( timer_t *timerID, int expireMS, int intervalMS )

{

    struct sigevent te;

    struct itimerspec its;

    struct sigaction sa;

    int sigNo = SIGRTMIN;


    /* Set up signal handler. */

    sa.sa_flags = SA_SIGINFO;

    sa.sa_sigaction = timerHandler;

    sigemptyset(&sa.sa_mask);

    if (sigaction(sigNo, &sa, NULL) == -1) {

        perror("sigaction");

    }


    /* Set and enable alarm */

    te.sigev_notify = SIGEV_SIGNAL;

    te.sigev_signo = sigNo;

    te.sigev_value.sival_ptr = timerID;

    timer_create(CLOCK_REALTIME, &te, timerID);


    its.it_interval.tv_sec = 0;

    its.it_interval.tv_nsec = intervalMS * 1000000;

    its.it_value.tv_sec = 0;

    its.it_value.tv_nsec = expireMS * 1000000;

    timer_settime(*timerID, 0, &its, NULL);


    return 1;

}


int main()

{

    makeTimer(&firstTimerID, 500, 500); //2ms

    makeTimer(&secondTimerID,900, 900); //10ms

    //makeTimer(&thirdTimerID, 100, 100); //100ms


    while(1)

    {

    }

    return 0;

}