2019.03.20王苛震
Posted ymfqq
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2019.03.20王苛震相关的知识,希望对你有一定的参考价值。
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <sys/time.h> 4 #include <signal.h> 5 #include <string.h> 6 #include <unistd.h> 7 8 #define MAX 1024 9 10 typedef struct { 11 int sec; 12 void (*any)(void *); 13 char *s; 14 } alrm_st; 15 16 static alrm_st *p[MAX]; 17 static int flag; 18 19 void anytimer_alarm(int sec_cus, void (*any_cus)(void *s), void *s_cus); 20 static void clk_first(void); 21 static int _getpos(void); 22 static void clk_fun(int s); 23 24 static void any1(void *s) 25 { 26 printf("%s", (char *)s); 27 fflush(NULL); 28 } 29 30 static void any2(void *s) 31 { 32 printf("%s", (char *)s); 33 fflush(NULL); 34 } 35 36 static void any3(void *s) 37 { 38 printf("%s", (char *)s); 39 fflush(NULL); 40 } 41 42 int main(void) 43 { 44 anytimer_alarm(3, any1, "hello"); 45 anytimer_alarm(2, any2, "world"); 46 anytimer_alarm(5, any3, "apue"); 47 48 /* 49 **world*hello**apue****** 50 */ 51 while (1) { 52 write(1, "*", 1); 53 sleep(1); 54 } 55 56 return 0; 57 } 58 59 void anytimer_alarm(int sec_cus, void (*any_cus)(void *s), void *s_cus) 60 { 61 int td = 0; 62 63 if (flag == 0) { //加载信号 64 clk_first(); 65 flag == 1; 66 } 67 td = _getpos(); //获取当前索引值 68 if (td == -1) 69 return; 70 71 p[td] = malloc(sizeof(alrm_st)); //开辟静态区空间 72 if (p[td] == NULL) 73 return; 74 75 p[td]->sec = sec_cus; //配置结构体成员 76 p[td]->any = any_cus; 77 p[td]->s = malloc(sizeof(*s_cus)); //开辟结构体存字符串的静态区空间 78 if (p[td]->s == NULL) { 79 free(p[td]); 80 return; 81 } 82 strcpy(p[td]->s, s_cus); //拷贝参数中的字符串 83 } 84 85 static void clk_first(void) //设置信号与时钟 86 { 87 struct itimerval val, oldval; 88 struct sigaction act, oldact; 89 90 val.it_interval.tv_sec = 1; 91 val.it_interval.tv_usec = 0; 92 val.it_value.tv_sec = 1; 93 val.it_value.tv_usec = 0; 94 setitimer(ITIMER_REAL, &val, &oldval); 95 96 act.sa_handler = clk_fun; 97 sigemptyset(&act.sa_mask); 98 act.sa_flags = 0; 99 sigaction(SIGALRM, &act, &oldact); 100 } 101 102 static int _getpos(void) //1024上限 从头分配 103 { 104 for (int i = 0; i < MAX; i++) { 105 if (p[i] == NULL) { 106 return i; 107 } 108 } 109 return -1; //无空间 110 } 111 112 static void clk_fun(int s) //函数倒计时 113 { 114 for (int i = 0; i < MAX; i++) { 115 if (p[i] != NULL) { 116 p[i]->sec -= 1; 117 if (p[i]->sec == 0) 118 p[i]->any(p[i]->s); 119 } 120 } 121 }
[email protected]:~/apue_my/hw3$ ./clock //终端编译结果 **world*hello**apue******^C
以上是关于2019.03.20王苛震的主要内容,如果未能解决你的问题,请参考以下文章