编写一个程序库,实现定时器的功能,它能为用户提供在同一进程中多次使用的定时器。

#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触发

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值