tags:

views:

70

answers:

3

Is it possible in Perl to install only one signal handler for all the signals it receive? The reason behind this is, I am not aware of what signal my Perl code will get at run time. One way I can see is that point all the available signals to my custom signal handler, but I don't want to go this way. Is there any easy way to do this? something like:

$SIG{'ALL'} = 'sigHandler';
+2  A: 

Off the top of my head,

foreach my $key (keys %SIG) {
    $SIG{$key} = \&sighandler
}

This is probably a bad idea though. You should only catch whatever signals you know you can handle. Different signals should not be all handled in the same way. Do you really want SIGINT to be handled the same way as SIGCHILD for example? SIGHUP? SIGUSR1?

Daenyth
mobrule
@morbule: Thanks. My perl-fu is a tad rusty.
Daenyth
+4  A: 
$SIG{$_} = 'sigHandler' for keys %SIG;

If you want to treat __WARN__ and __DIE__ differently,

use Config;
$SIG{$_} = 'sigHandler' for split ' ', $Config{sig_name};
mobrule
+9  A: 

You really don't want to do this. Only install signal handlers for the signals you need to handle differently than default (which we can't help you with, since you don't mention what kind of application you are writing).

In most normal cases, you don't have to write signal handlers at all -- the defaults are set up to do exactly what you need. You should read perldoc perlipc right now so you are aware of what cases you have that differ from normality.

You can modify more than one signal at once with the sigtrap pragma: it is useful for adding handlers for normally-untrapped signals, or for making normal error handling more strict.

# install a trivial handler for all signals, as a learning tool
use sigtrap 'handler' => \&my_handler, 'signal';
sub my_handler
{
    print "Caught signal $_[0]!\n";
}
Ether
This is definitely a useful exercise for testing/debugging and learning about signal handling. For example, you could log the signal, unset the signal handler, and raise the signal again (to be handled in the default manner). But definitely not a best practice for production code.
mobrule