Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

signals

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';
like image 717
Anil Vishnoi Avatar asked Oct 01 '10 16:10

Anil Vishnoi


People also ask

Can you have multiple signal handlers?

Only one signal handler can be installed per signal. Only the latest installed handler will be active.

Do signal handlers run concurrently?

Signal handlers run concurrently with main program (in same process).

Can signal handlers be interrupted by other signal handlers?

Signal handlers can be interrupted by signals, including their own. If a signal is not reset before its handler is called, the handler can interrupt its own execution. A handler that always successfully executes its code despite interrupting itself or being interrupted is async-signal-safe.

Which function is used to establish a new handler for a signal?

Using signal These basic actions are used to define a signal handler using the signal function defined by the ISO/ANSI standard: Call the signal or sigaction functions to identify a handler for the signal in the beginning of the program or at some point before the signal may occur.


2 Answers

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";
}
like image 157
Ether Avatar answered Oct 14 '22 21:10

Ether


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

If you want to treat __WARN__ and __DIE__ differently,

use Config;
$SIG{$_} = 'sigHandler' for split ' ', $Config{sig_name};
like image 37
mob Avatar answered Oct 14 '22 20:10

mob