标签:str gem char atexit int struct == 初始 pre
1 #ifndef __ALRM_H 2 #define __ALRM_H 3 4 #define MAX 1024 5 6 typedef void (*any_t)(void *s); 7 8 typedef struct { 9 int times; 10 any_t any; 11 void *p; 12 }alarm_t; 13 14 //初始化 15 int alrm_init(int t, any_t a, void *ptr); 16 17 //销毁 18 void akrm_destroy(int i); 19 20 #endif
1 #include <stdlib.h> 2 #include <sys/time.h> 3 #include <signal.h> 4 #include <errno.h> 5 #include <unistd.h> 6 7 #include "alrm.h" 8 9 static alarm_t *arr[MAX]; 10 11 static int inited; 12 static struct sigaction oldact; 13 static struct itimerval olditv; 14 15 void alrm_destroy(int i); 16 17 static int get_pos(void) 18 { 19 for(int i; i<MAX; i++){ 20 if(NULL == arr[i]) 21 return i; 22 } 23 return -1; 24 } 25 26 static void alrm_handler(int s) 27 { 28 for(int i = 0; i< MAX; i++){ 29 if(NULL != arr[i]){ 30 if(arr[i]->times > 1) 31 arr[i]->times -= 1; 32 }else { 33 arr[i]->any(arr[i]->p); 34 alrm_destroy(i); 35 } 36 } 37 } 38 //信号行为 时钟恢复 39 static void moduler_unload(void) 40 { 41 sigaction(SIGALRM, &oldact, NULL); 42 setitimer(ITIMER_REAL, &olditv, NULL); 43 } 44 45 static void moduler_load(void) 46 { 47 struct sigaction act; 48 struct itimerval itv; 49 50 act.sa_handler = alrm_handler; 51 act.sa_flags = 0; 52 sigemptyset(&(act.sa_mask)); 53 sigaction(SIGALRM, &act, &oldact); 54 55 itv.it_interval.tv_sec = 1; 56 itv.it_interval.tv_usec = 0; 57 58 itv.it_value.tv_sec = 1; 59 itv.it_value.tv_usec = 0; 60 setitimer(ITIMER_REAL, &itv, &olditv); 61 62 atexit(moduler_unload); 63 } 64 65 //初始化 66 int alrm_init(int t, any_t a, void *ptr) 67 { 68 alarm_t *alm = NULL; 69 int pos; 70 71 if(inited == 0){ 72 moduler_load(); 73 inited = 1; 74 } 75 alm = malloc(sizeof(*alm)); 76 if(NULL == alm) 77 return -ENOMEM; 78 alm->times = t; 79 alm->any = a; 80 alm->p = ptr; 81 82 pos = get_pos(); 83 if(pos < 0){ 84 free(alm); 85 return -ENOSPC; 86 } 87 arr[pos] = alm;
1 #include <stdio.h> 2 #include <unistd.h> 3 4 #include "alrm.h" 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 val1, val2, val3; 26 27 val1 = alrm_init(3, any1, "hello"); 28 val2 = alrm_init(2, any2, "world"); 29 val3 = alrm_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 }
88 return pos; 89 } 90 91 //销毁 92 void alrm_destroy(int i){ 93 free(arr[i]); 94 arr[i] = NULL; 95 }
标签:str gem char atexit int struct == 初始 pre
原文地址:https://www.cnblogs.com/ylx0506/p/10588893.html