#ifndef __ALRM_H
#define __ALRM_H #define MAX 1024 typedef void (*any_t)(void *s); typedef struct {
int times;
any_t any;
void *p;
}alarm_t; //初始化
int alrm_init(int t, any_t a, void *ptr); //销毁
void akrm_destroy(int i); #endif
 #include <stdlib.h>
#include <sys/time.h>
#include <signal.h>
#include <errno.h>
#include <unistd.h> #include "alrm.h" static alarm_t *arr[MAX]; static int inited;
static struct sigaction oldact;
static struct itimerval olditv; void alrm_destroy(int i); static int get_pos(void)
{
for(int i; i<MAX; i++){
if(NULL == arr[i])
return i;
}
return -;
} static void alrm_handler(int s)
{
for(int i = ; i< MAX; i++){
if(NULL != arr[i]){
if(arr[i]->times > )
arr[i]->times -= ;
}else {
arr[i]->any(arr[i]->p);
alrm_destroy(i);
}
}
}
//信号行为 时钟恢复
static void moduler_unload(void)
{
sigaction(SIGALRM, &oldact, NULL);
setitimer(ITIMER_REAL, &olditv, NULL);
} static void moduler_load(void)
{
struct sigaction act;
struct itimerval itv; act.sa_handler = alrm_handler;
act.sa_flags = ;
sigemptyset(&(act.sa_mask));
sigaction(SIGALRM, &act, &oldact); itv.it_interval.tv_sec = ;
itv.it_interval.tv_usec = ; itv.it_value.tv_sec = ;
itv.it_value.tv_usec = ;
setitimer(ITIMER_REAL, &itv, &olditv); atexit(moduler_unload);
} //初始化
int alrm_init(int t, any_t a, void *ptr)
{
alarm_t *alm = NULL;
int pos; if(inited == ){
moduler_load();
inited = ;
}
alm = malloc(sizeof(*alm));
if(NULL == alm)
return -ENOMEM;
alm->times = t;
alm->any = a;
alm->p = ptr; pos = get_pos();
if(pos < ){
free(alm);
return -ENOSPC;
}
arr[pos] = alm;
 #include <stdio.h>
#include <unistd.h> #include "alrm.h"
static void any1(void *s)
{
printf("%s", (char *)s);
fflush(NULL);
} static void any2(void *s)
{
printf("%s", (char *)s);
fflush(NULL);
} static void any3(void *s)
{
printf("%s", (char *)s);
fflush(NULL);
} int main(void)
{
int val1, val2, val3; val1 = alrm_init(, any1, "hello");
val2 = alrm_init(, any2, "world");
val3 = alrm_init(, any3, "apue"); /*
**world*hello**apue******
*/
while () {
write(, "*", );
sleep();
} return ;
}
     return pos;
} //销毁
void alrm_destroy(int i){
free(arr[i]);
arr[i] = NULL;
}
 
05-11 21:54