title: Linux, C, how to cancel a timer?
body: <p>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?</p>
  
  <p>For example, for the code in Paul Griffiths's answer to this thread: <a href="https://stackoverflow.com/questions/19758101/signal-handler-to-stop-timer-in-c">Signal Handler to stop Timer in C</a></p>
  
  <p>How do I cancel the timer in the signal_handler, if user stop the application by Ctrl+C before interval fired?</p>
  
  <pre><code>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, &amp;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;
  }
  </code></pre>