我想创建一个定时器,并将其设置为在60秒后仅触发一次。但是,在60秒到期之前,用户使用Ctrl+C取消了应用程序。我如何取消计时器并优雅地退出程序?
例如,对于Paul Griffiths在此线程中的代码答案:Signal Handler to stop Timer in C 如果用户在间隔触发之前通过Ctrl+C停止应用程序,我如何在signal_handler中取消计时器?
例如,对于Paul Griffiths在此线程中的代码答案:Signal Handler to stop Timer in C 如果用户在间隔触发之前通过Ctrl+C停止应用程序,我如何在signal_handler中取消计时器?
void signal_handler(int n)
{
//Ctrl+C
if (n == SIGINT){
PRINT_ERR("Ctrl+C");
**//how to cancel it_val here???**
}
exit (1);
}
bool timer_fired = false;
void TimerStop(int signum) {
printf("Timer ran out! Stopping timer\n");
timer_fired = true;
}
struct itimerval it_val;
void TimerSet(struct itimerval it_val, int interval)
{
printf("starting timer\n");
it_val.it_value.tv_sec = interval;
it_val.it_value.tv_usec = 0;
it_val.it_interval.tv_sec = 0;
it_val.it_interval.tv_usec = 0;
if (signal(SIGALRM, TimerStop) == SIG_ERR) {
perror("Unable to catch SIGALRM");
exit(1);
}
if (setitimer(ITIMER_REAL, &it_val, NULL) == -1) {
perror("error calling setitimer()");
exit(1);
}
}
int main()
{
signal(SIGINT, signal_handler);
TimerSet(it_val, INTERVAL);
while ( !timer_fired )
do_something();
return 0;
}