定時器是比較常用的功能。一直很好奇底層的實現方法。我想最終是使用了CPU的硬體定時器中斷機制。有兩種實現方法,第一種精度較低,實際使用中並不多。
如果不要求很精確的話,用 alarm() 和 signal() 就夠了
unsigned int alarm(unsigned int seconds)
專門為SIGALRM訊號而設,在指定的時間seconds秒後,將向進程本身發送SIGALRM訊號,又稱為鬧鐘時間。進程調用alarm後,任何以前的alarm()調用都將無效。如果參數seconds為零,那麼進程內將不再包含任何鬧鐘時間。如果調用alarm()前,進程中已經設定了鬧鐘時間,則返回上一個鬧鐘時間的剩餘時間,否則返回0。參考樣本如下:
1 #include<iostream> 2 #include<unistd.h> 3 #include<signal.h> 4 using namespace std; 5 6 void signal_fun(int sig) 7 { 8 cout<<"alarm, sig="<<sig<<endl; 9 alarm(2);10 return;11 }12 13 int main(void)14 {15 signal(SIGALRM, signal_fun);16 alarm(2);17 18 while(1) pause();19 20 return 0;21 }
int setitimer(int which, const struct itimerval *value, struct itimerval *ovalue));
setitimer()比alarm功能強大,支援3種類型的定時器:
ITIMER_REAL : 以系統真實的時間來計算,它送出SIGALRM訊號。
ITIMER_VIRTUAL : 以該行程真正有執行的時間來計算,它送出SIGVTALRM訊號。
ITIMER_PROF : 以行程真正有執行及在核心中所費的時間來計算,它送出SIGPROF訊號。
Setitimer()第一個參數which指定定時器類型(上面三種之一);第二個參數是結構itimerval的一個執行個體;第三個參數可不做處理。
Setitimer()調用成功返回0,否則返回-1。
參考樣本如下:
1 #include <stdio.h> 2 #include <time.h> 3 #include <sys/time.h> 4 #include <stdlib.h> 5 #include <signal.h> 6 int count = 0; 7 void set_timer() 8 { 9 struct itimerval itv, oldtv;10 itv.it_interval.tv_sec = 5;11 itv.it_interval.tv_usec = 0;12 itv.it_value.tv_sec = 5;13 itv.it_value.tv_usec = 0;14 15 setitimer(ITIMER_REAL, &itv, &oldtv);16 }17 18 void sigalrm_handler(int sig)19 {20 count++;21 printf("timer signal.. %d\n", count);22 }23 24 int main()25 {26 printf("%d,%d,%d\n", SIGSEGV, SIGALRM, SIGRTMIN);27 signal(SIGALRM, sigalrm_handler);28 set_timer();29 while (count < 1000)30 {}31 exit(0);32 }