반응형
POSIX Timer 예제
#include#include #include #include #include #include using namespace std; #define SIGTIMER (SIGRTMAX) #define ONESHOTTIMER (SIGRTMAX-1) timer_t SetTimer(int signo, int sec, int mode); void SignalHandler(int signo, siginfo_t * info, void *context); timer_t timerid,oneshotTimer; int main() { struct sigaction sigact; sigemptyset(&sigact.sa_mask); sigact.sa_flags = SA_SIGINFO; sigact.sa_sigaction = SignalHandler; // Set up sigaction to catch signal if (sigaction(SIGTIMER, &sigact, NULL) == -1) { perror("sigaction failed"); return -1; } // Set up sigaction to catch signal if (sigaction(ONESHOTTIMER, &sigact, NULL) == -1) { perror("sigaction failed"); return -1; } // Establish a handler to catch CTRL+C and use it for exiting sigaction(SIGINT, &sigact, NULL); timerid = SetTimer(SIGTIMER, 500, 1); oneshotTimer = SetTimer(ONESHOTTIMER, 5000, 0); while(1); return 0; } timer_t SetTimer(int signo, int sec, int mode) { struct sigevent sigev; timer_t timerid; struct itimerspec itval; struct itimerspec oitval; // Create the POSIX timer to generate signo sigev.sigev_notify = SIGEV_SIGNAL; sigev.sigev_signo = signo; sigev.sigev_value.sival_ptr = &timerid; if (timer_create(CLOCK_REALTIME, &sigev, &timerid) == 0) { itval.it_value.tv_sec = sec / 1000; itval.it_value.tv_nsec = (long)(sec % 1000) * (1000000L); if (mode == 1) { itval.it_interval.tv_sec = itval.it_value.tv_sec; itval.it_interval.tv_nsec = itval.it_value.tv_nsec; } else { itval.it_interval.tv_sec = 0; itval.it_interval.tv_nsec = 0; } if (timer_settime(timerid, 0, &itval, &oitval) != 0) { perror("time_settime error!"); } } else { perror("timer_create error!"); return (timer_t)-1; } return timerid; } void SignalHandler(int signo, siginfo_t * info, void *context) { if (signo == SIGTIMER) { puts("Periodic timer"); } else if (signo == ONESHOTTIMER) { puts("One-short timer"); } else if (signo == SIGINT) { timer_delete(oneshotTimer); timer_delete(timerid); perror("Ctrl + C cached!\n"); exit(1); } }
'Programming > C/C++' 카테고리의 다른 글
INADDR_LOOPBACK (0) | 2015.05.22 |
---|---|
1byte unsigned char 를 4비트 단위로 쪼개서 사용하기 (0) | 2015.05.22 |
내 네트워크상의 모든 컴퓨터 이름 목록과 IP 주소 출력 (0) | 2012.12.20 |
Text 마지막에서 10줄 읽어오기 (0) | 2012.11.19 |
Visual Studio 2012 Thread Library 사용 (1) | 2012.08.21 |
C++ UAC Class (0) | 2012.02.28 |
[c/c++] srand 사용시 주의사항 (0) | 2011.08.22 |
VC Express. Dll 또는 Lib 프로젝트에서 버전을 표시 하자. (1) | 2009.08.11 |