1 #ifndef __ALRM_HW_H
2 #define __ALRM_HW_H
3
4 #define ALARM_MAX 1024
5
6 typedef void (*any_t)(void *s);
7
8 //初始化
9 int anytimer_alarm_init(int times, any_t any, void *s);
10
11 //销毁
12 void anytimer_alarm_destroy(int ad);
13
14 #endif
1 #include <errno.h>
2 #include <stdlib.h>
3 #include <sys/time.h>
4 #include <unistd.h>
5 #include <signal.h>
6
7 #include "alrm_hw.h"
8
9 int anytimer_alarm_init(int times, any_t any, void *s);
10 static void moduler_load(void);
11 static void moduler_unload(void);
12 static void alrm_handler(int s);
13 static int get_pos(void);
14 void anytimer_alarm_destroy(int ad);
15
16 typedef struct {
17 int sec;
18 any_t fun;
19 void *ptr;
20 } alarm_t;
21
22 static alarm_t *arr[ALARM_MAX];
23 static int inited;
24 static struct sigaction oldact;
25 static struct itimerval olditv;
26
27 //初始化
28 int anytimer_alarm_init(int times, any_t any, void *s)
29 {
30 alarm_t *p = NULL;
31 int pos;
32
33 if (0 == inited) {
34 moduler_load();
35 inited = 1;
36 }
37
38 p = malloc(sizeof(*p));
39 if (NULL == p)
40 return -ENOMEM;
41 p->sec = times;
42 p->fun = any;
43 p->ptr = s;
44
45 pos = get_pos();
46 if (pos < 0) {
47 free(p);
48 return -ENOSPC;
49 }
50
51 arr[pos] = p;
52 return pos;
53 }
54
55 static void moduler_load(void)
56 {
57 struct sigaction act;
58 struct itimerval itv;
59
60 act.sa_handler = alrm_handler;
61 act.sa_flags = 0;
62 sigemptyset(&act.sa_mask);
63 sigaction(SIGALRM, &act, &oldact);
64
65 itv.it_interval.tv_sec = 1;
66 itv.it_interval.tv_usec = 0;
67 itv.it_value.tv_sec = 1;
68 itv.it_value.tv_usec = 0;
69 setitimer(ITIMER_REAL, &itv, &olditv);
70
71 atexit(moduler_unload);
72 }
73
74 static void moduler_unload(void)
75 {
76 sigaction(SIGALRM, &oldact, NULL);
77 setitimer(ITIMER_REAL, &olditv, NULL);
78 }
79
80 static void alrm_handler(int s)
81 {
82 for (int i = 0; i < ALARM_MAX; i++) {
83 if (NULL != arr[i]) {
84 if (arr[i]->sec > 1) {
85 arr[i]->sec -= 1;
86 } else {
87 arr[i]->fun(arr[i]->ptr);
88 anytimer_alarm_destroy(i);
89 }
90 }
91 }
92 }
93
94 static int get_pos(void)
95 {
96 for (int i = 0; i < ALARM_MAX; i++) {
97 if (NULL == arr[i])
98 return i;
99 }
100 return -1;
101 }
102
103 //销毁
104 void anytimer_alarm_destroy(int ad)
105 {
106 free(arr[ad]);
107 arr[ad] = NULL;
108 }
1 #include <stdio.h>
2 #include <unistd.h>
3 #include "alrm_hw.h"
4
5 static void any1(void *s)
6 {
7 printf("%s", (char *)s);
8 fflush(NULL);
9 }
10
11 static void any2(void *s)
12 {
13 printf("%s", (char *)s);
14 fflush(NULL);
15 }
16
17 static void any3(void *s)
18 {
19 printf("%s", (char *)s);
20 fflush(NULL);
21 }
22
23 int main(void)
24 {
25 int t1, t2, t3;
26
27 t1 = anytimer_alarm_init(3, any1, "hello");
28 t2 = anytimer_alarm_init(2, any2, "world");
29 t3 = anytimer_alarm_init(5, any3, "apue");
30
31 /*
32 **world*hello**apue******
33 */
34 while (1) {
35 write(1, "*", 1);
36 sleep(1);
37 }
38
39 return 0;
40 }