anytime
作者:互联网
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<unistd.h> 4 #include<sys/time.h> 5 #include<signal.h> 6 #include<string.h> 7 8 #define BUFMAX 1024 9 10 11 static void alarm_handler(int s); 12 13 14 static int init_mod; 15 static struct sigaction oldact; 16 typedef void (*anytm_t)(void *s); 17 typedef struct myalarm{ 18 int sec; 19 anytm_t anytm; 20 //void (*anytm_t)(void *s); 21 char * arg; 22 }tim_t; 23 static tim_t *buf[BUFMAX] = {}; 24 25 26 //关闭闹钟 27 static void buf_break(void) 28 { 29 struct itimerval itv; 30 sigaction(SIGALRM,&oldact,NULL); 31 itv.it_interval.tv_sec = 0; 32 itv.it_interval.tv_usec = 0; 33 itv.it_value.tv_sec = 0; 34 itv.it_value.tv_usec = 0; 35 setitimer(ITIMER_REAL,&itv,NULL); 36 init_mod = 0; 37 } 38 39 40 static void func(void *s) 41 { 42 printf("%s",(char *)s); 43 fflush(NULL); 44 45 } 46 47 static void alarm_init(void) 48 { 49 struct itimerval itv; 50 itv.it_interval.tv_sec = 1; 51 itv.it_interval.tv_usec = 0; 52 itv.it_value.tv_sec = 1; 53 itv.it_value.tv_usec = 0; 54 55 struct sigaction act; 56 act.sa_handler = alarm_handler; 57 sigemptyset(&act.sa_mask); 58 act.sa_flags = 0; 59 60 setitimer(ITIMER_REAL,&itv,NULL); 61 sigaction(SIGALRM,&act,&oldact); 62 init_mod = 1; 63 64 65 } 66 static void alarm_handler(int s) 67 { 68 for(int i = 0;i < 1024;i++) 69 { 70 if(buf[i] != NULL) 71 { 72 buf[i]->sec--; 73 if(buf[i]->sec == 0) 74 { 75 buf[i]->anytm(buf[i]->arg); 76 free(buf[i]); 77 buf[i] = NULL; 78 } 79 } 80 } 81 } 82 83 84 85 static int time_init(int n,anytm_t anytm,void *p) 86 { 87 tim_t *t = NULL; 88 int i; 89 if(0==init_mod) 90 alarm_init(); 91 t = malloc(sizeof(tim_t) + strlen(p)); 92 if(t == NULL) 93 return -1; 94 95 for(int i = 0;i < BUFMAX;i++) 96 { 97 if(buf[i] == NULL) 98 { 99 break; 100 } 101 } 102 t->sec = n; 103 t->anytm = anytm; 104 strcpy(t->arg,(char *)p); 105 buf[i] = t; 106 return i; 107 108 109 } 110 111 void anytime_destroy(void) 112 { 113 buf_break(); 114 for(int i = 0;i < 1024;i++) 115 { 116 if(buf[i] != NULL) 117 { 118 free(buf[i]); 119 buf[i] = NULL; 120 } 121 } 122 } 123 124 125 126 int main(void) 127 { 128 int i = 0; 129 130 time_init(2,func,"hello"); 131 time_init(4,func,"world"); 132 time_init(6,func,"uplooking"); 133 134 135 136 while(1) 137 { 138 write(1,"*",1); 139 sleep(1); 140 i++; 141 if(i == 6) 142 anytime_destroy(); 143 144 145 146 } 147 148 149 exit(0); 150 }
标签:int,void,anytime,init,itv,NULL,buf 来源: https://www.cnblogs.com/wyd111/p/10585723.html