http://qs321.pair.com?node_id=857359

saintmike has asked for the wisdom of the Perl Monks concerning the following question:

When setting a signal handler in a module, the problem arises that the application using the module already might have a signal handler set up for the signal in question.

So, for example, if a module FooFramework sets

$SIG{HUP} = sub { print "Framework handler!\n"; };
but the application FooApp has already set
$SIG{HUP} = sub { print "FooApp handler!\n"; };
then loading module FooFramework would actually disrupt the application by nuking its signal handler.

So, if FooFramework wants to play nice, it should check if there's already a SIG handler defined and, if so, stack its handler on top of it by wrapping around FooApp's handler:

my $old_handler = $SIG{HUP}; $SIG{HUP} = sub { print "Framework handler!\n"; $old_handler->(@_) if defined $old_handler; }
which works as long as FooApp doesn't set $SIG{HUP} to 'DEFAULT' or 'IGNORE'.

Now, this could be checked as well, but it feels like re-inventing the wheel. I'm wondering if there's a standard mechanism for handling these cases? Like, a %SIG slot with a ref to an array of handlers? Any help appreciated.

Replies are listed 'Best First'.
Re: Stacking Signal Handlers
by Anonymous Monk on Aug 26, 2010 at 03:51 UTC
Re: Stacking Signal Handlers
by Marshall (Canon) on Aug 27, 2010 at 11:07 UTC
    A signal is a super abbreviated message - its literally a "one bit message" on/off. A common use for this particular signal is to force a daemon to re-read its config file. The entry for $SIG{'HUP'} starts off as undefined. The signal handler when installed, is essentially the address of a subroutine that receives exactly ZERO parameters. Of course that sub could call a number of subs which also take no parameters.

    What that subroutine does is your business. Installing a signal handler is something that the main process code should do. Not something that happens because of the "use" statement of some module. The processing of this signal is a public interface that has application level not just module significance.

      Installing a signal handler is something that the main process code should do. Not something that happens because of the "use" statement of some module.
      As long as you're programming simple scripts in a bubble, that assumption might work.

      If, on the other hand, you're developing a framework to be used by others, you'll realize that this is a real-world problem that needs to be addressed -- ideally by a cookbook solution.