Search code examples
ctimersleepsetitimer

Interval Timer not firing signal at specified time interval


I want to call timer_handler function at every 2 seconds regardless of execution time of timer_handler function here is my code

#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/time.h>

void timer_handler (int signum)
{
 static int count = 0;
 sleep(1);
 printf ("timer expired %d times %d signum \n", ++count, signum);
}

int main ()
{
 struct sigaction sa;
 struct itimerval timer;

 /* timer_handler as the signal handler for SIGVTALRM. */
 memset (&sa, 0, sizeof (sa));
 sa.sa_handler = &timer_handler;
 sigaction (SIGVTALRM, &sa, NULL);

 /* Configure the timer to expire after 2000 msec... */
 timer.it_value.tv_sec = 2;
 timer.it_value.tv_usec = 0;
 /* ... and every 2000 msec after that. */
 timer.it_interval.tv_sec = 2;
 timer.it_interval.tv_usec = 0;
 /* Start a virtual timer. It counts down whenever this process is
   executing. */
 setitimer (ITIMER_VIRTUAL, &timer, NULL);
 /* Do busy work. */
 while (1);
}

As per above code it should print timer expired 1 times 26 signum at every two second but its prints on every 3 seconds which includes sleep time so i want to call that function on every 2 seconds. I don't know where i am doing wrong If any other library is able to do this please let me know Thank you


Solution

  • Why not use wall-clock time?

    To do so

    • install the signal handler for SIGALRM instead of SIGVTALRM and
    • specify ITIMER_REAL instead of ITIMER_VIRTUAL.

    Unrelated but important: Signal handlers may only call async-signal-safe functions. printf() is not one of those. For a list of the latter click here and scroll down.