One problem you have is the first timer trigger ends the pause
call and your program terminates. The pause
command is described like this:
The pause function suspends program execution until a signal arrives whose action is either to execute a handler function, or to terminate the process.
Another problem is that you're using the "interval" incorrectly. That value is supposed to be the number that the timer is reset to if it is a repeating timer. So to trigger every second, you need to set it to 1
.
Now, if you want it to run for 30 seconds, you'll need to maintain a counter, and then reset the timer after that counter is finished. Finally, you need to keep re-pausing until enough interrupts have been serviced.
Try this:
#include <sys/time.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
volatile int timer_remain = 30;
void alarmhandler()
{
static struct itimerval notimer = { 0 };
printf( "Timer triggered\n" );
if( --timer_remain == 0 )
{
setitimer( ITIMER_REAL, ¬imer, 0 );
}
}
int main()
{
struct itimerval timerval = { 0 };
timerval.it_value.tv_sec = 1;
timerval.it_interval.tv_sec = 1;
signal( SIGALRM, alarmhandler );
setitimer( ITIMER_REAL, &timerval, 0 );
while( timer_remain > 0 )
{
pause();
}
printf( "Done\n" );
return 0;
}
One last thing to note is that there's no guarantee that the timer will be delivered every second if system load is high.