其他分享
首页 > 其他分享> > 2019.3.23王允 多任务计时器anytime

2019.3.23王允 多任务计时器anytime

作者:互联网

  1 #include<stdio.h>
  2 #include<unistd.h>
  3 #include<stdlib.h>
  4 #include<signal.h>
  5 #include<sys/time.h>
  6 #include<errno.h>
  7 #include<string.h>
  8 
  9 #define MAXTIM 1024
 10 typedef void (*any_timer)(void *);
 11 
 12 typedef struct{
 13     int sec;
 14     any_timer anytm;
 15     char *arg;
 16 }tim_t;
 17 
 18 static tim_t *jobs[MAXTIM];
 19 static int inited;
 20 static struct sigaction oldact;
 21 
 22 static int get_pos(void)
 23 {
 24     int i;
 25     for(i=0;i<MAXTIM;i++)
 26     {
 27         if(jobs[i]==NULL)
 28             return i;
 29     }
 30     return -1;
 31 }
 32 
 33 static void alrm_handler(int s)
 34 {
 35     int i;
 36     for(i=0;i<MAXTIM;i++)
 37     {
 38         if(jobs[i]!=NULL)
 39         {
 40             jobs[i]->sec--;
 41             if(jobs[i]->sec<=0)
 42             {
 43                 jobs[i]->anytm(jobs[i]->arg);
 44                 free(jobs[i]);
 45                 jobs[i]=NULL;
 46             }
 47         }
 48     }
 49     
 50 }
 51 
 52 static void moduler_load(void)
 53 {
 54     struct sigaction act;
 55     struct itimerval itv;
 56 
 57     itv.it_interval.tv_sec = 1;
 58     itv.it_interval.tv_usec = 0;
 59     itv.it_value.tv_sec = 1;
 60     itv.it_value.tv_usec = 0;
 61     setitimer(ITIMER_REAL, &itv, NULL);
 62 
 63     act.sa_handler = alrm_handler;
 64     act.sa_flags = 0;
 65     sigemptyset(&act.sa_mask);
 66     sigaction(SIGALRM, &act, &oldact);
 67         
 68 }
 69 static int anytimer_alarm(int time,any_timer any_tm,void *s)
 70 {
 71     tim_t *t=NULL;
 72     int pos;
 73     if(inited==0)
 74     {
 75         moduler_load();
 76         inited=1;
 77     }
 78     t=malloc(sizeof(*t));
 79     if(NULL==t)
 80         return -ENOMEM;
 81     t->arg=malloc(strlen(s));
 82     if(NULL==t->arg)
 83     {
 84         free(t);
 85         return -1;
 86     }
 87     t->sec=time;
 88     t->anytm=any_tm;
 89     t->arg=s;
 90     pos=get_pos();
 91     if(pos<0)
 92     {
 93         free(t);
 94         return -ENOSPC;
 95     }
 96     jobs[pos]=t;
 97     return pos;
 98 }
 99 
100 static void _any(void *s)
101 {
102     printf("%s",(char *)s);
103     fflush(NULL);
104 }
105 
106 int main(void)
107 {
108     anytimer_alarm(3,_any,"hello");
109     anytimer_alarm(2,_any,"world");
110     anytimer_alarm(5,_any,"apue");
111 
112     while(1)
113     {
114         write(1,"*",1);
115         sleep(1);        
116     }
117 
118     exit(0);    
119 }

 

标签:23,int,void,anytime,2019.3,static,arg,itv,include
来源: https://www.cnblogs.com/yunge123/p/10585452.html