# setitimer question



## bsd_newbie (Feb 27, 2009)

The following program prints "woke up" only once. I was expecting
it will do so 5 times at the 10, 11, 12, 13, 14 seconds...

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

#define INTERVAL 10

void wakeup(int signo)
{
    printf("woke up\n");
}

typedef struct elem_ {
    int index;
    struct itimerval timer;
} elem_t;

elem_t arr[5];

main()
{
    struct itimerval timer;
    struct sigaction sa;    /* Signal handler specification structure */
    int i;


    sa.sa_handler = wakeup;
    sa.sa_flags = SA_RESTART;

    if (sigaction(SIGALRM, &sa, 0) < 0) {
        perror("sigaction");
    }    

    for (i = 0; i < 5; i++) {
        memset(&arr_.timer, 0, sizeof(struct itimerval));
        arr.timer.it_value.tv_usec = 0;
        arr.timer.it_value.tv_sec = i + 10;
        setitimer(ITIMER_REAL, &arr.timer, NULL);
    }

    while (1) {
        ;
    }
}_


----------



## lyuts (Feb 27, 2009)

If I'm not mistaken then you can't have concurrent timers. I mean only one at a time. If you want several timers, then you have to simulate concurrent timers by calculating offsets/deltas for your timers (but sort them in ascending order).

If you need timers 10, 20, 30, 40 ... then you need to have delta's array which will be 10, 10, 10, 10...

But here comes another problem. Such approach doesn't give 100% that each of your timers will fire at that precise moment that you have set. A timer has a step and if it is (let's say) 5 sec, and you have timers for 10, 23, 25 seconds then the second timer will fire 2 seconds later.


----------



## trev (Feb 27, 2009)

man setitimer:


```
[b]The system provides each process with three interval timers[/b], defined in
     <sys/time.h>.  The getitimer() system call returns the current value for
     the timer specified in which in the structure at value.  The setitimer()
     system call sets a timer to the specified value (returning the previous
     value of the timer if ovalue is not a null pointer).
```


----------



## ephemera (Feb 27, 2009)

note that the program takes 14 = 10 + i (i=4) secs, so i think that every time setitimer() was called the timer was rearmed.


----------



## lyuts (Mar 3, 2009)

trev said:
			
		

> man setitimer:
> 
> 
> ```
> ...



Yes, you are right, but did you see the description of those timers?

ITIMER_REAL
    counts real (wall clock) time, and sends the SIGALRM signal 
ITIMER_VIRTUAL
    counts process virtual (user CPU) time, and sends the SIGVTALRM signal 
ITIMER_PROF
    counts user and system CPU time, and sends the SIGPROF signal; it is intended for interpreters to use for profiling. 

I suppose the timers you described (the ones you want to use) are ITIMER_REAL timers.


----------

