Second signal call in sighandler - what for?

2019-02-26 00:31发布

问题:

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.

回答1:

Handling Signals

The call to signal establishes signal handling for only one occurrence of a signal. Before the signal-handling function is called, the library resets the signal so that the default action is performed if the same signal occurs again. Resetting signal handling helps to prevent an infinite loop if, for example, an action performed in the signal handler raises the same signal again. If you want your handler to be used for a signal each time it occurs, you must call signal within the handler to reinstate it. You should be cautious in reinstating signal handling. For example, if you continually reinstate SIGINT handling, you may lose the ability to interrupt and terminate your program.

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 call signal() if the program needs to continue handling signals using a non-default handler.



回答2:

(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 use sigaction.



回答3:

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 why signal() is called again in the signal handler.



标签: c signals