linux下的C語言開發(定時器)

來源:互聯網
上載者:User

定時器是我們需要經常處理的一種資源。那linux下面的定時器又是怎麼一回事呢?其實,在linux裡面有一種進程中資訊傳遞的方法,那就是訊號。這裡的定時器就相當於系統每隔一段時間給進程發一個定時訊號,我們所要做的就是定義一個訊號處理函數。

 1 #include <stdio.h> 2 #include <time.h> 3 #include <sys/time.h> 4 #include <stdlib.h> 5 #include <signal.h> 6  7 static int count = 0; 8 static struct itimerval oldtv; 9 10 void set_timer()11 {12     struct itimerval itv;13     itv.it_interval.tv_sec = 1;14     itv.it_interval.tv_usec = 0;15     itv.it_value.tv_sec = 1;16     itv.it_value.tv_usec = 0;17     setitimer(ITIMER_REAL, &itv, &oldtv);18 }19 20 void signal_handler(int m)21 {22     count ++;23     printf("%d\n", count);24 }25 26 int main()27 {28     signal(SIGALRM, signal_handler);29     set_timer();30     while(count < 10000);31     exit(0);32     return 1;33 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.