linux的下兩種定時器實現

來源:互聯網
上載者:User

定時器是比較常用的功能。一直很好奇底層的實現方法。我想最終是使用了CPU的硬體定時器中斷機制。有兩種實現方法,第一種精度較低,實際使用中並不多。

  • alarm方式

如果不要求很精確的話,用 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 }
  • settimer方式 

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 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.