I was asked a few times about %SIG localization and have stumbled upon
this problem myself. Either it's a $SIG{PIPE}, $SIG{__WARN__},
$SIG{__DIE__} or $SIG{CHLD} -- the most relevant sigs for mod_perl.

Here is the problem. Consider this code:

MyRun.pm:
---------
package MyRun;

$SIG{__DIE__} = \&mydie;

sub dienow{
  print "Content-type: text/plain\n\n";
  print "before die\n";
  die("I'm dying...");
  print "after die\n";
}

sub mydie{
  my $why = shift;
  print "Die was trapped: $why\n";
  exit;
}
1;

die.pl
------
use MyRun;
MyRun::dienow();

works OK, the __DIE__ sig gets trapped, no problem. But you don't want to
write code like this since it affects the whole process!

So I add local before $SIG{__DIE__}:

  local $SIG{__DIE__} = \&mydie;

and my sighandler is ignored. Notice that if I move all the code into a
single script, local does work. Actually not the code, but only the
sighandler assignment.

MyRun.pm:
---------
package MyRun;

sub dienow{
  print "Content-type: text/plain\n\n";
  print "before die\n";
  die("I'm dying...");
  print "after die\n";
}

sub mydie{
  my $why = shift;
  print "Die was trapped: $why\n";
  exit;
}
1;

die.pl
------
use MyRun;

$SIG{__DIE__} = \&MyRun::mydie;
MyRun::dienow();

Surprising, but this appears to work. I didn't see this problem covered in
perlipc. (It behaves completely identical without mod_perl).  Is it a bug
or a feature? 

So for my understanding it appears to be the bug in Perl. Since you cannot
reassign the handler after this was trapped with local and if you don't
use local() you affect the whole process, which you don't want to. So this
code won't work correctly as expected: 

sub mydie{
  my $why = shift;
  print "Die was trapped: $why\n";
  local $SIG{__DIE__} = \&mydie; # reassign the sig
  exit;   
}

The above code is required on *some* OSes, because the SIG gets cleared
after it was called for the first time. 

Also I couldn't make it work inside the modules, where the sig was
supposed to be localized. e.g with SIG{CHLD} when forking a process, to
prevent zombies.

This is it.

_______________________________________________________________________
Stas Bekman    mailto:[EMAIL PROTECTED]      http://www.stason.org/stas
Perl,CGI,Apache,Linux,Web,Java,PC     http://www.stason.org/stas/TULARC
perl.apache.org    modperl.sourcegarden.org   perlmonth.com    perl.org
single o-> + single o-+ = singlesheaven    http://www.singlesheaven.com

Reply via email to