main.c
1 #include <stdio.h> 2 #include <unistd.h> 3 4 #include "myalarm.h" 5 6 int main(void) 7 { 8 anytimer_alarm(3, any1, "hello"); 9 anytimer_alarm(2, any2, "world"); 10 anytimer_alarm(5, any3, "apue"); 11 /* 12 **world*hello**apue****** 13 */ 14 while (1) { 15 write(1, "*", 1); 16 sleep(1); 17 } 18 return 0; 19 }
myalrm.c
1 #include <stdio.h> 2 #include <signal.h> 3 #include <stdlib.h> 4 #include <sys/time.h> 5 #include <unistd.h> 6 #include <errno.h> 7 8 #include "myalarm.h" 9 10 int inited=0; 11 12 typedef struct anyalarm 13 { 14 int sec; 15 void (*fcntl)(void *); 16 char *str; 17 }ANYALRM; 18 19 ANYALRM *alr[ALRSIZE]; 20 static struct sigaction oldact; 21 static struct itimerval olditv; 22 23 static void alrm_handler(int s) 24 { 25 for(int i=0;i<ALRSIZE;i++){ 26 if(alr[i] != NULL){
alr[i]->sec-=1;0 27 if(alr[i]->sec =0= 0){ 28 alr[i]->fcntl(alr[i]->str); 29 free(alr[i]); 30 }
} 31 } 33 } 34 35 void moduler_load() 36 { 37 struct sigaction act; 38 struct itimerval itv; 39 40 act.sa_handler = alrm_handler; 41 act.sa_flags = 0; 42 sigemptyset(&act.sa_mask); 43 sigaction(SIGALRM, &act, &oldact); 44 45 itv.it_interval.tv_sec = 1; 46 itv.it_interval.tv_usec = 0; 47 itv.it_value.tv_sec = 1; 48 itv.it_value.tv_usec = 0; 49 setitimer(ITIMER_REAL, &itv, &olditv); 50 51 atexit(moduler_unload); 52 } 53 54 // 信号行为和时钟的恢复 55 void moduler_unload() 56 { 57 sigaction(SIGALRM, &oldact, NULL); 58 setitimer(ITIMER_REAL, &olditv, NULL); 59 } 60 61 void any1(void *s) 62 { 63 printf("%s\n",(char *)s); 64 } 65 66 void any2(void *s) 67 { 68 printf("%s\n",(char *)s); 69 } 70 71 void any3(void *s) 72 { 73 printf("%s\n",(char *)s); 74 } 75 76 int alr_init(int sec, void (*fcntl)(void *),char *str) 77 { 78 ANYALRM *alrm=NULL; 79 //第一次调用 80 if(inited == 0){ 81 moduler_load(); 82 inited=1; 83 } 84 alrm=malloc(sizeof(ANYALRM)); 85 if(alrm == NULL){ 86 fprintf(stderr,"malloc is failed!\n"); 87 } 88 alrm->sec=sec; 89 alrm->fcntl=fcntl; 90 alrm->str=str; 91 for(int i=0;i<ALRSIZE;i++){ 92 if(alr[i] == NULL) 93 { 94 alr[i]=alrm; 95 return i; 96 } 97 } 98 return -1; 100 } 101 102 void anytimer_alarm(int sec, void (*fcntl)(void *),char *str) 103 { 104 if(alr_init(sec,fcntl,str) < 0){ 105 fprintf(stderr,"alr_init failed\n"); 106 return ; 107 } 109 }
myalarm.h
1 #ifndef __MYALARM_H 2 #define __MYALARM_H 3 4 #define ALRSIZE 1024 5 6 void any1(void *s); 7 void any2(void *s); 8 void any3(void *s); 9 10 void anytimer_alarm(int sec, void (*fcntl)(void *),char *str); 11 12 int alr_init(int sec, void (*fcntl)(void *),char *str); 13 14 15 void alarm_handler(int s); 16 17 int alr_init(int sec,void (*fcntl)(void *),char *str); 18 19 void moduler_load(void); 20 21 void moduler_unload(void); 22 23 #endif
makefile
1 main : main.o myalarm.o 2 gcc main.o myalarm.o -o main 3 clean : 4 rm -rf *.o main