anytimer.c
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <sys/time.h>
#include <errno.h>
#include <wait.h>
#include "anytimer.h"
struct timer *job[MAXS];
static int inited = 0;
static struct sigaction older;
static struct itimerval olditv;
struct timer
{
int pos;
void *data;
any anyfunc;
};
int anytimer_print(void)
{
int i;
for( i = 0; i < MAXS; i++)
{
if(job[i] != NULL && job[i]->pos == 0)
{
kill(getpid(), SIGRTMIN);
return i;
}
}
return -1;
}
void int_handler()
{
int i, j;
int ret;
pid_t pid;
for(i = 0; i < MAXS; i++)
{
if(job[i] != NULL)
job[i]->pos -= 1;
}
pid = fork();
if(pid == 0)
{
ret = anytimer_print();
if(ret != -1)
job[ret]->anyfunc(job[ret]->data);
else
{
sigprocmask(SIG_SETMASK, &olders, NULL);
}
exit(0);
}
ret = anytimer_print();
write(1,"*",1);
wait(NULL);
}
static void moduler_unload(void)
{
sigaction(SIGALRM, &older, NULL);
setitimer(ITIMER_REAL, &olditv, NULL);
}
void moduler_load()
{
struct sigaction act;
struct itimerval itv;
act.sa_handler = int_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGALRM, &act, &older);
itv.it_interval.tv_sec = 1;
itv.it_interval.tv_usec = 0;
itv.it_value.tv_sec = 1;
itv.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &itv, &olditv);
atexit(moduler_unload);//钩子函数
}
int find_arr() // 寻找空数组下标
{
int i;
for(i = 0; i < MAXS; i++)
{
if(job[i] == NULL)
return i;
}
return -1;
}
void anytimer_alarm(int n,any anytime, void *p)
{
struct timer *me = NULL;
int ret;
int i;
if(inited == 0)
{
moduler_load();
inited = 1;
}
me = malloc(sizeof(struct timer));
if(me == NULL)
{
fprintf(stderr,"malloc is faild !\n");
exit(-1);
}
me->pos = n;
me->data = p;
me->anyfunc = anytime;
ret = find_arr(); // 寻找空数组下标
if(ret == -1)
{
fprintf(stderr, "find arr is faild!\n");
free(me);
exit(-1);
}
job[ret] = me;
}
void anytimer_destroy(void)
{
int i;
for(i = 0; i < MAXS; i++)
{
if(job[i] != NULL)
free(job[i]);
job[i] = NULL;
}
}
anytimer.h
#ifndef __ANYTIMER_H
#define __ANYTIMER_H
#define MAXS 1024
typedef void( *any)(void*);
void anytimer_alarm(int n,any anytime, void *p);
void anytimer_destroy(void);
#endif
main.c
#include <stdio.h>
#include <stdlib.h>
#include <wait.h>
#include <sys/types.h>
#include <unistd.h>
#include "anytimer.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)
{
anytimer_alarm(3, any1, "hello");
anytimer_alarm(2, any2, "world");
anytimer_alarm(5, any3, "apue");
while (1)
{
}
anytimer_destroy();
return 0;
}
~