linux 使用setittimer 如何设定一段时间后让方程停止
#include<stdio.h>#include<signal.h>#include<sys/time.h>#include<stdlib.h>#defineINTER...
#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
#include <stdlib.h>
#define INTERVAL 5
int howmany = 0;
void alarm_wakeup (int i)
{
struct itimerval tout_val;
signal(SIGALRM,alarm_wakeup);
howmany += INTERVAL;
printf("\n%d sec up partner, Wakeup!!!\n",howmany);
tout_val.it_interval.tv_sec = 0;
tout_val.it_interval.tv_usec = 0;
tout_val.it_value.tv_sec = INTERVAL; /* 10 seconds timer */
tout_val.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &tout_val,0);
}
void exit_func (int i)
{
signal(SIGINT,exit_func);
printf("\nBye Bye!!!\n");
exit(0);
}
int main ()
{
struct itimerval tout_val;
tout_val.it_interval.tv_sec = 0;
tout_val.it_interval.tv_usec = 0;
tout_val.it_value.tv_sec = INTERVAL; /* 10 seconds timer */
tout_val.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &tout_val,0);
signal(SIGALRM,alarm_wakeup); /* set the Alarm signal capture */
signal(SIGINT,exit_func);
while (1)
{
//printf("!");
}
return 0;
}
output:
5 sec up partner, Wakeup!!!
10 sec up partner, Wakeup!!!
15 sec up partner, Wakeup!!!
20 sec up partner, Wakeup!!!
25 sec up partner, Wakeup!!!
30 sec up partner, Wakeup!!!
^C
Bye Bye!!!
这个例子是开始间隔5s后执行程序 之后每5s运行程序一次
但是没设置停止时间
请问如何设置程序到达一定时间停止?
比如5分钟?
谢谢!! 展开
#include <signal.h>
#include <sys/time.h>
#include <stdlib.h>
#define INTERVAL 5
int howmany = 0;
void alarm_wakeup (int i)
{
struct itimerval tout_val;
signal(SIGALRM,alarm_wakeup);
howmany += INTERVAL;
printf("\n%d sec up partner, Wakeup!!!\n",howmany);
tout_val.it_interval.tv_sec = 0;
tout_val.it_interval.tv_usec = 0;
tout_val.it_value.tv_sec = INTERVAL; /* 10 seconds timer */
tout_val.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &tout_val,0);
}
void exit_func (int i)
{
signal(SIGINT,exit_func);
printf("\nBye Bye!!!\n");
exit(0);
}
int main ()
{
struct itimerval tout_val;
tout_val.it_interval.tv_sec = 0;
tout_val.it_interval.tv_usec = 0;
tout_val.it_value.tv_sec = INTERVAL; /* 10 seconds timer */
tout_val.it_value.tv_usec = 0;
setitimer(ITIMER_REAL, &tout_val,0);
signal(SIGALRM,alarm_wakeup); /* set the Alarm signal capture */
signal(SIGINT,exit_func);
while (1)
{
//printf("!");
}
return 0;
}
output:
5 sec up partner, Wakeup!!!
10 sec up partner, Wakeup!!!
15 sec up partner, Wakeup!!!
20 sec up partner, Wakeup!!!
25 sec up partner, Wakeup!!!
30 sec up partner, Wakeup!!!
^C
Bye Bye!!!
这个例子是开始间隔5s后执行程序 之后每5s运行程序一次
但是没设置停止时间
请问如何设置程序到达一定时间停止?
比如5分钟?
谢谢!! 展开
1个回答
展开全部
setitimer()触发SIGALRM信号,alarm_wakeup()再调用setitimer()递归运行,主程序死循环等待这个信号系统的反复执行。要终止它,有2种方法:
1、主程序while{}中判断howmany == 300时,调用raise(SIGINT)终止或者直接break出循环就行了。
2、alarm_wakeup()中在setitimer()前,判断howmany == 300时调用raise(SIGINT)一样可以终止程序执行。
1、主程序while{}中判断howmany == 300时,调用raise(SIGINT)终止或者直接break出循环就行了。
2、alarm_wakeup()中在setitimer()前,判断howmany == 300时调用raise(SIGINT)一样可以终止程序执行。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询