付铖 2019 3.23

  1 #include<stdio.h>
  2 #include<unistd.h>
  3 #include<signal.h>
  4 #include<stdlib.h>
  5 #include<string.h>
  6 #include<sys/time.h>
  7 
  8 #define MAX_LONG 20
  9 typedef struct
 10 {
 11     int scand;
 12     void (* hs)(void * );
 13     char  put[100];
 14 }st;
 15 
 16 static st * arr[MAX_LONG];
 17 
 18 void any_put(void * s)
 19 {
 20     printf("%s",(char *)s);
 21     fflush(NULL);
 22 }
 23 void anytimer_alarm(int time,void(* any)(void * ),char * s);
 24 int main(void)
 25 {
 26     anytimer_alarm(3,any_put,"hello");
 27     anytimer_alarm(2,any_put,"world");
 28     anytimer_alarm(5,any_put,"aque");
 29     while(1)
 30     {
 31         write(1,"*",1);
 32         sleep(1);
 33     }
 34     return 0;
 35 }
 36 
 37 void printf_handler(int i)
 38 {
 39     (arr[i]->hs)(arr[i]->put);
 40 }
 41 void ala(int s)
 42 {
 43 //    alarm(1);
 44     int i;
 45     for(i = 0; i < MAX_LONG;i++)
 46     {
 47         if(arr[i] != NULL)
 48         {
 49             if(arr[i]->scand  == -1)
 50             {
 51                 arr[i] = NULL;
 52                 free(arr[i]);
 53                 continue ;
 54             }
 55             arr[i]->scand  -= 1;
 56             if(arr[i]->scand == 0)
 57                 printf_handler(i);
 58         }
 59     }
 60 
 61 }
 62 static int anytimer_init(int time,void (*any)(void *),char *s)
 63 {
 64     int i;
 65     st * p = NULL;
 66     for(i = 0; i < MAX_LONG ; i++)
 67     {
 68         if(arr[i] == NULL)
 69             break;
 70     }
 71     if(i == MAX_LONG)
 72         return -1;
 73     p = malloc(sizeof(st));
 74     if(NULL == p)
 75         return -1;
 76     p->scand = time;
 77     p->hs = any;
 78     strcpy(p->put,s);
 79     arr[i] = p;
 80     //改变信号的行为
 81 #if 1
 82     struct sigaction act;
 83     act.sa_flags = 0;
 84     act.sa_handler = ala;
 85     sigemptyset(&act.sa_mask);
 86     sigaction(SIGALRM,&act,NULL);
 87     //一秒一次
 88     struct itimerval value;
 89     value.it_interval.tv_sec = 1;
 90     value.it_interval.tv_usec = 0;
 91     value.it_value.tv_sec = 1;
 92     value.it_value.tv_usec = 0;
 93     setitimer(ITIMER_REAL,&value,NULL);
 94 
 95 #endif
 96 
 97 #if 0
 98     signal(14,ala);
 99     alarm(1);
100 #endif
101 
102     return i;
103 }
104 void anytimer_alarm(int time,void(* any)(void * ),char * s)
105 {
106     if(time < 0)
107         return ;
108     if(NULL == s)
109         return;
110     anytimer_init(time,any,s);
111 }
 

猜你喜欢

转载自www.cnblogs.com/fc724/p/10584936.html