#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <signal.h>
#define MAX 10 //定时器最多个数
int i=0,t=1; //i表示定时器个数,t表示从程序开始执行到目前经过的时间
struct Timer
{
inttotal_time; //定时时间
intleft_time; //还剩多少秒
void(*func)(); //定时器超时后要执行的函数
}myTimer[MAX]; //存放所有定时器的数组
void setTimer(int t,int l,void(*f)()) //设置一个新的计时器
{
struct Timer new;
new.total_time=t;
new.left_time=l;
new.func=f;
myTimer[i++]=new;
}
void Timer1()
{
printf("------Timer1: --Hello a!\n");
}
void Timer2()
{
printf("------Timer1: --Hello b!\n");
}
void Timer3()
{
printf("------Timer1: --Hello c!\n");
}
void timeout() //定时器超时后要执行的函数
{
intj;
for(j=0;j<i;j++)
{
myTimer[j].left_time--;
if(myTimer[j].left_time!=0)
;
else
{
myTimer[j].func(); //定时器到执行函数
myTimer[j].left_time=myTimer[j].total_time; //循环计时
}
}
}
int main()
{
printf("ProgramStarting!\n");
setTimer(3,3,Timer1); //第一个totaltime,第二个lefttime,第三个函数
setTimer(4,4,Timer2);
setTimer(5,5,Timer3);
signal(SIGALRM,timeout); //接到SIGALRM信号,则执行timeout函数
while(1)
{
sleep(1);
printf("Time:%d\n",t++);
kill(getpid(),SIGALRM); //每隔一秒发送一个SIGALRM
}
exit(0);
}
运行结果如图:
每隔3秒的倍数timer1触发,每隔4秒的倍数timer2触发,每隔5秒的倍数timer3触发