본문 바로가기

Programming/C/C++

C Timer 만들어 사용하기.

[출처] : http://linuxspot.tistory.com/28

리눅스 API 중 타이머를 설정하고 콜백함수를 등록하는 직접적인 API는 안타깝게도 없는것 같습니다. 하지만 시그널을 이용하여 거의 유사한 동작을 수행할 수 있습니다. 시그널을 이용한 방법 중 alarm 함수 또는  setitimer 함수를 이용하는 방법이 있는데 alarm의 경우 최소 interval이 1초라는 제약 때문에 사실상 사용하기 힘든 방법이라고 볼 수 있습니다.

setitimer를 이용한 방법은 itimerval 구조체를 사용하여 usec 단위의 해상도를 가지는 타이머 이벤트를 생성할 수 있기 때문에 일반적으로 생각하는 타이머 콜백 함수에 적합하다고 볼 수 있습니다. 

다음은 시그널 핸들러를 설정한 뒤 interval을 설정하고 setitimer 함수를 호출하여 타이머를 동작시키는 예제입니다.

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>

void timer_handler (int signum)
{
       
static int count = 0;
        printf
("timer expired %d timers\n", ++count);
}

int main ()
{
       
struct sigaction sa;
       
struct itimerval timer;

       
/* Install timer_handler as the signal handler for SIGVTALRM. */
        memset
(&sa, 0, sizeof (sa));
        sa
.sa_handler = &timer_handler;
        sigaction
(SIGVTALRM, &sa, NULL);

       
/* Configure the timer to expire after 250 msec... */
        timer
.it_value.tv_sec = 0;
        timer
.it_value.tv_usec = 250000;

       
/* ... and every 250 msec after that. */
        timer
.it_interval.tv_sec = 0;
        timer
.it_interval.tv_usec = 250000;

       
/* Start a virtual timer. It counts down whenever this process is executing. */
        setitimer
(ITIMER_VIRTUAL, &timer, NULL);

       
/* Do busy work.  */
       
while (1);
}



참고자료



'Programming > C/C++' 카테고리의 다른 글

c언어 매크로 사용법 - 1. #, ## 연산자  (0) 2014.12.05
HEX dump  (0) 2014.12.01
C++ 마스터로 가는길..  (0) 2014.10.07
printf format  (0) 2014.09.04
epoll example  (0) 2014.07.28