Howard Shane
Howard Shane

Reputation: 956

Linux, C, how to cancel a timer?

I want to create a timer and set it to fire only once after 60 seconds. But before it fired on the 60 seconds, user cancel the application by Ctrl+C. How do I cancel my timer and exit the program gracefully?

For example, for the code in Paul Griffiths's answer to this thread: Signal Handler to stop Timer in C

How do I cancel the timer in the signal_handler, if user stop the application by Ctrl+C before interval fired?

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;
}

Upvotes: 3

Views: 9253

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798536

Call setitimer(2) again with a time of 0 to disable the timer.

A timer which is set to zero (it_value is zero or the timer expires and it_interval is zero) stops.

Upvotes: 8

Related Questions