Skip to content
Advertisement

“Alarm clock” message on linux

I’m working on a project written in C and I’m using alarms. In the beginning of the code I use sigaction() to initialize the alarm:

struct sigaction sa;
sa.sa_handler = alarm_handler;
sigaction(SIGALRM, &sa, NULL);

Then I call the alarm with the alarm() function in a loop:

while(){
    alarm(mySeconds);
}

The program sends the first alarm and runs the handler function, but when he sends the second one a message appears on the output stream:

"Alarm clock"

I don’t know why this keeps happening. Thank you.

Advertisement

Answer

You leave most the variables of struct sigaction uninitialized, you need to do

struct sigaction sa;
memset(&sa, 0, sizeof sa);
sa.sa_handler = alarm_handler;

Note also what the alarm documentation says if you are calling alarm() again before any current alarm has expired: ” In any event any previously set alarm() is canceled.”. So calling it millions of times a second like in your loop is probably not a good idea, you’re constantly resetting the alarm.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement