1. 程式人生 > >Linux C++Timer(用訊號量實現)

Linux C++Timer(用訊號量實現)

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

static int count = 0;
static struct itimerval oldtv;

void set_timer()
{
    struct itimerval itv;//結構體的定義在Timer.h
    itv.it_interval.tv_sec = 1;
    itv.it_interval.tv_usec = 0
; itv.it_value.tv_sec = 1; itv.it_value.tv_usec = 0; setitimer(ITIMER_REAL, &itv, &oldtv);//向核心註冊一個timer訊號 } void signal_handler(int m) { count ++; printf("%d\n", count); } int main() { /*核心收到setitemer時觸發的訊號,會啟用SIGALRM signal這個函式是訊號量註冊,只要收到SIGALRM就會呼叫signal_handler */ signal(SIGALRM, signal_handler); set_timer(); while
(count < 10000); exit(0); return 1; }