Anil Vishnoi
Anil Vishnoi

Reputation: 1392

Can I set a single signal handler for all signals in Perl?

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';

Upvotes: 9

Views: 3123

Answers (3)

Ether
Ether

Reputation: 53994

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";
}

Upvotes: 12

mob
mob

Reputation: 118695

$SIG{$_} = 'sigHandler' for keys %SIG;

If you want to treat __WARN__ and __DIE__ differently,

use Config;
$SIG{$_} = 'sigHandler' for split ' ', $Config{sig_name};

Upvotes: 7

Daenyth
Daenyth

Reputation: 37461

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?

Upvotes: 3

Related Questions