## Wednesday, May 15, 2013

### Anatomy of A Periodic Program

The program body is here,

http://disi.unitn.it/~abeni/RTOS/periodic-1.c

First to mention that a periodic program is that it is activated periodically, i.e. the program wakes up periodically (it is ready for execution). Under Linux kernel, you could trace such wake up events (sched_wake_up) through ftrace. The sample program uses a real-time timer ITIMER_REAL to create periodic interrupts. The timer is set initially 2000000 us (=2s) and thence 5000us (5ms).

start_periodic_timer(2000000, 5000);


In further detail, that is

signal(SIGALRM, sighand);


Notice that sighand is the name of the call-back function. Whenever there a SIGALRM fires within the program, the function sighand is called. Though in the example it is a do-nothing function. The signal function registers sighand as the call-back, but it doesn't execute it.

The following does the job to set periods and the first round offset (this is to ensure the periodicity since we are still initializing the timer before the real periodic part comes). The timer ITIMER_REAL fires the signal SIGALRM when the timer count decreases to zero (expires), as a consequence, signal goes executed.

setitimer(ITIMER_REAL, &t, NULL);

So there are periodic interrupts on which a futile function is run (whence the program wakes up). The following infinite loop does sleeping till the signal is fired (pause()), then an in-genuine job_body() is under way. The job body function is "controlled" within 5ms such that all interrupt signals are captured on-time.

    while(1) {
wait_next_activation();
job_body();
}


### Conclusion

An implementation of periodic programs follows this pattern,

void *PeriodicTask(void *arg)
{
<initialization>;
<start periodic timer, period = T>;
while (cond) {