理解进程及信号的概念
掌握进程编程和信号控制函数的使用
编写一个程序库,实现定时器的功能,它能为用户提供在同一进程中多次使用的定时器
源码:
#include<stdio.h> #include<stdlib.h> #include<unistd.h>
#include<signal.h> #include<time.h> #include<sys/time.h>
#define N 100 //设置最大的定时器个数
int i=0,t=0;//i代表定时器的个数;t表示时间,逐秒递增
struct Timer{
int total_time; //定时器时长
int rest_time; //剩余时间
int flag; //倒计时结束时要执行的动作的标识
int end;
}myTimer[N]; //用于保存定时器
void setTimer(int t,int f) //设置计时器
{
struct Timer timer;
timer.total_time = t;
timer.rest_time = t;
timer.flag = f;
timer.end = 0;
myTimer[i++] = timer;}
void timeout() //判断定时器是否超时,及其超时响应的动作
{
printf("time: %ds\n",t++);
int j;
for(j=0;j<i;j++)
{
if(myTimer[j].end) //若该计时器被贴上结束标签,则不再判断
{ continue; }
if(myTimer[j].rest_time != 0)
{ myTimer[j].rest_time--; }
else
{ myTimer[j].end = 1;
switch(myTimer[j].flag)
{ case 1:
printf("提示音1:bibibi~ time out!\n");
break;
case 2:
printf("提示音2:biubiubiu~ time out!\n");
break;
case 3:
printf("提示音3:clickclickclick~ time out!\n");
break;
} } } }
int main()
{ setTimer(3,1); //时长3秒,选择提示音1
setTimer(5,2); //时长5秒,选择提示音2
setTimer(7,3); //时长7秒,选择提示音3
signal(SIGALRM,timeout); //收到SIGALRM信号,则执行timeout函数
while(t<8)
{ sleep(1); //每隔一秒发送一个SIGALRM信号
kill(getpid(),SIGALRM); //发送SIGALRM信号
}
printf("所有定时器均已超时\n");
exit(0); }
结果: