多個定時器的實現 c語言

來源:互聯網
上載者:User
 1 #include<stdio.h>
2 #include<stdlib.h>
3 #include<signal.h>
4
5 #define N 100 //設定最大的定時器個數
6
7 int i = 0,t = 1; //i代表定時器的個數;t表示時間,逐秒遞增,先sleep(1),故初始為1
8
9 struct Timer //Timer結構體,用來儲存一個定時器的資訊
10 {
11 int left_time; //還剩left_time秒
12 }myTimer[N]; //定義Timer類型的數組,用來儲存所有的定時器
13
14 void setTimer(int time) //建立一個計時器
15 {
16 struct Timer a;
17 a.left_time = time;
18 myTimer[i++] = a;
19 }
20
21 void timeout() //判斷定時器是否逾時,以及逾時時所要執行的動作
22 {
23 printf("Time: %d\n",t++);
24 int j;
25 for (j = 0; j < i; j++) {
26 if(myTimer[j].left_time != 1) { // 為1不為0,因為第一次沒有先減
27 myTimer[j].left_time--;
28 }
29 else {
30 printf("myTimer[%d] end\n", j);
31 }
32 }
33 }
34
35 int main() //測試函數,定義三個定時器
36 {
37 setTimer(6);
38 setTimer(7);
39 setTimer(8);
40 if (signal(SIGALRM, timeout) == SIG_ERR) {//接到SIGALRM訊號,則執行timeout函數
41 printf("can't catch SIGALRM\n");
42 }
43 while(1) {
44 sleep(1);
45 kill(getpid(), SIGALRM); //每隔一秒發送一個SIGALRM, getpid取得進程識別碼
46 }
47 exit(0);
48 }
相關文章

聯繫我們

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