0

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);
}
Rachid K.
  • 4,490
  • 3
  • 11
  • 30
Snowybluesky
  • 47
  • 2
  • 7
  • What's a "linux die page"? – Jens Mar 11 '21 at 07:05
  • You’re not touching the struct in any way after the pause so it will always have the same values. Does the timer still fire? – Sami Kuhmonen Mar 11 '21 at 07:09
  • @SamiKuhmonen I have now tried setting the timer values after the first pause() and before the second resume() call. However, the timer's value are still no automatically decremented as they were when the first resume() call was made. – Snowybluesky Mar 11 '21 at 19:54

0 Answers0