I want to repeatedly set up a SIGALRM and wait until it goes off, then do it again. In my handler function I have:
void handler(int signum)
{
struct itimerval timer;
struct sigaction sa;
sa.sa_handler = handler;
timer.it_interval.tv_sec = 0;
timer.it_interval.tv_usec = 0;
timer.it_value.tv_usec = 0;
timer.it_value.tv_sec = 1000;
sigaction(SIGALRM, &sa, 0);
setitimer(ITIMER_REAL, &timer, 0);
printf("pause for me\n");
pause();
}
and in my main I have:
int main(void)
{
handler(0);
return 0;
}
However, all it does is repeat twice then stalls. I want it to continue repeating. What’s the problem?
struct sigactionhas several fields which you are not initializing. The stack garbage you happen to get the first few times works and then you hit a case where it does not and your handler is not installed. You should test thesigaction()return. When you get-1print a message includingerrno.You should call
sigaction()once (frommain()or similar). It will “stick” if you don’t set theSA_RESETHANDflag. Then your other existing code will probably work.For more accurate repeating timing you should take advantage of
struct itimerval‘sit_intervalwhich lets you set the next timer value so it will commence immediately when the current one fires.