1827474 Members
1748 Online
109965 Solutions
New Discussion

Perl Question

 
SOLVED
Go to solution
Steve Start
Advisor

Perl Question

Hello Perl Experts:

How do I temporarily replace a signal handler inside a perl function and then restore the previous signal handler?

TIA,
Steve
5 REPLIES 5
A. Clay Stephenson
Acclaimed Contributor
Solution

Re: Perl Question

This is rather easy if I correctly understand your question.

my $Flag = 0;

sub my_local_handler
{
$SIG{INT} = \&my_local_handler;
++$Flag;
return(0);
} # my_local_handler

sub my_function
{
local $SIG{INT} = \&my_local_handler;
...
...
return(0);
} # my_function

The key is the "local" scope. When my_function falls out of scope then the signal handler for SIGINT reverts to its prior value.

If it ain't broke, I can fix that.
James R. Ferguson
Acclaimed Contributor

Re: Perl Question

Hi Steve:

Use a 'local' declaration for your handler. For instance:

sub mything {
local $SIG{INT} = \&myhandler;
...
}

Regards!

...JRF...
Steve Start
Advisor

Re: Perl Question

Thanks guys. That was very quick.

A. Clay, why do you do this inside the signal handler?

sub my_local_handler
{
$SIG{INT} = \&my_local_handler;
++$Flag;
return(0);
} # my_local_handler

It looks like you are setting the signal handler to itself. Was this a typo?

Thanks,
Steve
A. Clay Stephenson
Acclaimed Contributor

Re: Perl Question

No Steve, t'weren't no typo nor was it no mistake neither. It was (probably) paranoia on my part leftover from signal handling in C in the dim mists of time. Consider what would happen if the process received another SIGINT while already processing a SIGINT. Resetting the signal handler to itself does no harm but is probably not necessary in modern versions of UNIX and Perl but the paranoid programmer will include the signal redirection in order to make truly portable code.
If it ain't broke, I can fix that.
A. Clay Stephenson
Acclaimed Contributor

Re: Perl Question

Oh, and I should add that the truly paranoid programmer also knows that signal handlers should be short and sweet. Do no more than absolutely necessary and then return. It depends upon how re-entrant the code is at the lowest levels -- and this applies to C and Perl.

If it ain't broke, I can fix that.