I'm trying to make a timer that can be paused/resumed with itimer.
I found this stackoverflow page with a suggested method. I've read the linux man page, and I've also tried using getitimer to save the timer, though it still does not work.
In the below code sample, I get 5000, 4537, 4537 and 4537 for d1, d2, d3 and d4, and I am attempting to get something like 5000, 4537, 4536, 4000.
Is there a way I can make it so that the timer value decreases after resuming?
Thank you for suggestions,
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/time.h>
#include <string.h>
struct itimerval old_timer;
void resume(){
setitimer(ITIMER_REAL, &old_timer, NULL);
}
void pause(){
struct itimerval zero_timer = { 0 };
setitimer(ITIMER_REAL, &zero_timer, &old_timer);
}
void timer_handler(){
puts("RING RING");
}
int main(){
struct sigaction sa;
memset(&sa, 0, sizeof (sa));
sa.sa_handler = timer_handler;
sigaction(SIGALRM, &sa, NULL);
old_timer.it_interval.tv_usec = 5000;
old_timer.it_interval.tv_sec = 0;
old_timer.it_value.tv_usec = 5000;
old_timer.it_value.tv_sec = 0;
resume();
long int d1 = old_timer.it_value.tv_usec;
puts("delay1");
pause();
long int d2 = old_timer.it_value.tv_usec;
for(int i=0; i<10; i++){ puts("delay2"); }
resume();
long int d3 = old_timer.it_value.tv_usec;
for(int i=0; i<10; i++){ puts("delay3"); }
long int d4 = old_timer.it_value.tv_usec;
for(int i=0; i<10; i++){ puts("delay4"); }
printf("%ld\n",d1);
printf("%ld\n",d2);
printf("%ld\n",d3);
printf("%ld\n",d4);
}