1. 程式人生 > >2019.03.20王苛震

2019.03.20王苛震

turn lda signal flush 配置 gem code fin 結果

  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 }
kkj@:~/apue_my/hw3$ ./clock       //終端編譯結果
**world*hello**apue******^C

2019.03.20王苛震