Recently I found some code which uses signal
:
286 static void sighandler( int signum )
287 {
288 alarmed = 1;
289 signal( signum, sighandler );
290 }
291
292 void set_alarm( int seconds )
293 {
294 alarmed = 0;
295 signal( SIGALRM, sighandler );
296 alarm( seconds );
297 }
I have some troubles to figure out why do I need to call signal
2 times, especially, why do I need to call signal
in sighandler
? I know what the above code does but dont understand why do I need to call signal
2 times.
Handling Signals
The
signal()
function defines the handling of the next received signal only, after which the default handling is reinstated. So it is necessary for the signal handler to callsignal()
if the program needs to continue handling signals using a non-default handler.(1) Calling
signal
two or more times is not unusual. It's just setting up two handlers for 2 different signals.(2) Older unix systems used to reset a signals disposition to default after a handler was invoked. This code is reestablishing the handler.
The GNU
man (2) signal
page has a couple of paragraphs devoted to this in the "portability" section. Actually one of several reasons to usesigaction
.There are systems where, if
signal()
is called with a function, the signal handler is reset to default after the first signal is caught (I haven't found out on the fly if it's defined to be so). That's the reason whysignal()
is called again in the signal handler.