I was using a periodic timer and taking times between when two SIGALRM signals are received. what I observed was that itimer might expires a little before or little after the time I set. e.g. if I set it for 1m sec , it might expires at 0.9998msec or 1.0023msec.
Shouldn’t the timer expiration would always be greater than what is set? less time taken is what I dont understand.
here’s my code:
enter code here
#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
#include <stdlib.h>
#include <time.h>
#define INTERVAL 1000
struct timespec ti[100];
int s=0;
void ex(int i)
{int d=0;
struct timespec t[100],s1,s2;
for(d=0;d<99;d++)
{
s1= ti[d];
s2= ti[d+1];
printf("%u:%u\t%u:%u\t", s1.tv_sec, s1.tv_nsec, s2.tv_sec, s2.tv_nsec);
if ((s2.tv_nsec- s1.tv_nsec)<0) {
t[d].tv_sec = s2.tv_sec-s1.tv_sec-1;
t[d].tv_nsec = 1000000000 +s2.tv_nsec -s1.tv_nsec;
} else {
t[d].tv_sec = s2.tv_sec-s1.tv_sec;
t[d].tv_nsec = s2.tv_nsec-s1.tv_nsec;
}
printf("%u:%u\n",t[d].tv_sec,t[d].tv_nsec);
}
exit(0);
}
void alarm_wakeup (int i)
{
clock_gettime(CLOCK_MONOTONIC, &ti[s]);
s++;
if(s==100)
{ ex(0);
}
}
void main ()
{
struct itimerval tout_val;
tout_val.it_interval.tv_sec = 0;
tout_val.it_interval.tv_usec = INTERVAL;
tout_val.it_value.tv_sec = 0;
tout_val.it_value.tv_usec = INTERVAL;
setitimer(ITIMER_REAL, &tout_val,0);
signal(SIGALRM,alarm_wakeup); /* set the Alarm signal capture */
signal(SIGINT,ex);
while (1)
{
}
}
When the timer expires, the signal is raised and the timer is rescheduled.
However, there can be a delay between the signal being raised and the signal being handled – if the process isn’t running already, it has to be rescheduled. This means that there is a potentially variable delay between the actual expiration of the timer and when the
clock_gettime()call in your signal handler runs.If this delay before the
clock_gettime()call is higher one iteration than the next, then the time between theclock_gettime()calls will be slightly less than 1ms even though there was a 1ms gap between the subsequent timer expiries.In diagrammatic form:
You can see that the longer delay before the second signal handler ran made the third signal appear to be “early”, even though the underlying timer was not.