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 }