I'm having troubles understanding the timer values filled by setitimer
.
I have the following code
#include <sys/time.h>
#include <stdio.h>
#include <signal.h>
struct itimerval defaultTimer = {{0, 2}, {0, 2}};
struct itimerval disabledTimer = {{0, 0}, {0, 0}};
void busy_wait(int iterations)
{
int count = 0;
for (int i = 0; i < iterations; i++)
{
count++;
}
}
int main()
{
// ignore SIGVTALRM
struct sigaction sa = { .sa_handler = SIG_IGN };
sigaction(SIGVTALRM, &sa, NULL);
if (setitimer(ITIMER_VIRTUAL, &defaultTimer, NULL) != 0)
{
return -1;
}
struct itimerval timer;
while (true)
{
setitimer(ITIMER_VIRTUAL, &disabledTimer, &timer);
setitimer(ITIMER_VIRTUAL, &timer, NULL);
busy_wait(10000000);
printf("timer.it_value: %lu.%lu\n", timer.it_value.tv_sec, timer.it_value.tv_usec);
printf("timer.it_interval: %lu.%lu\n", timer.it_interval.tv_sec, timer.it_interval.tv_usec);
}
}
As you see, I'm trying to "pause" the timer and immediately resume it. Running the code as it is generates output lines like these
timer.it_value: 0.4000
timer.it_interval: 0.4000
and nothing else. After the second call to setitimer
inside the loop, shouldn't the timer struct hold the values of the current timer? If so, how come I can't see the values of timer.it_value
decreasing?
Another weird thing, when removing the line busy_wait(10000000);
in the loop, I see different increasing values for timer.it_value
, for example
timer.it_value: 60.404000
timer.it_interval: 0.4000
...
timer.it_value: 489.256000
timer.it_interval: 0.4000
...
timer.it_value: 2391.108000
timer.it_interval: 0.4000
What do these numbers mean? according to the setitimer
manual
Timers decrement from it_value to zero, generate a signal, and reset to it_interval.
but that is in contrast with the results I see here.
Besides, why is timer.it_interval.tv_usec
has value 4000
? shouldn't it be 2
just as I set it?