#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/time.h>
#include<signal.h>
#include<string.h> #define BUFMAX 1024 static void alarm_handler(int s); static int init_mod;
static struct sigaction oldact;
typedef void (*anytm_t)(void *s);
typedef struct myalarm{
int sec;
anytm_t anytm;
//void (*anytm_t)(void *s);
char * arg;
}tim_t;
static tim_t *buf[BUFMAX] = {}; //关闭闹钟
static void buf_break(void)
{
struct itimerval itv;
sigaction(SIGALRM,&oldact,NULL);
itv.it_interval.tv_sec = ;
itv.it_interval.tv_usec = ;
itv.it_value.tv_sec = ;
itv.it_value.tv_usec = ;
setitimer(ITIMER_REAL,&itv,NULL);
init_mod = ;
} static void func(void *s)
{
printf("%s",(char *)s);
fflush(NULL); } static void alarm_init(void)
{
struct itimerval itv;
itv.it_interval.tv_sec = ;
itv.it_interval.tv_usec = ;
itv.it_value.tv_sec = ;
itv.it_value.tv_usec = ; struct sigaction act;
act.sa_handler = alarm_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = ; setitimer(ITIMER_REAL,&itv,NULL);
sigaction(SIGALRM,&act,&oldact);
init_mod = ; }
static void alarm_handler(int s)
{
for(int i = ;i < ;i++)
{
if(buf[i] != NULL)
{
buf[i]->sec--;
if(buf[i]->sec == )
{
buf[i]->anytm(buf[i]->arg);
free(buf[i]);
buf[i] = NULL;
}
}
}
} static int time_init(int n,anytm_t anytm,void *p)
{
tim_t *t = NULL;
int i;
if(==init_mod)
alarm_init();
t = malloc(sizeof(tim_t) + strlen(p));
if(t == NULL)
return -; for(int i = ;i < BUFMAX;i++)
{
if(buf[i] == NULL)
{
break;
}
}
t->sec = n;
t->anytm = anytm;
strcpy(t->arg,(char *)p);
buf[i] = t;
return i; } void anytime_destroy(void)
{
buf_break();
for(int i = ;i < ;i++)
{
if(buf[i] != NULL)
{
free(buf[i]);
buf[i] = NULL;
}
}
} int main(void)
{
int i = ; time_init(,func,"hello");
time_init(,func,"world");
time_init(,func,"uplooking"); while()
{
write(,"*",);
sleep();
i++;
if(i == )
anytime_destroy(); } exit();
}
04-28 22:07