Subject: | Signal-handling sample code is buggy |
Date: | Sun, 18 Oct 2009 14:57:23 -0700 (PDT) |
To: | bug-Sys-SigAction [...] rt.cpan.org |
From: | eponymous alias <eponymousalias [...] yahoo.com> |
Module Version: 0.11
Some of the example code for signal handling, such as:
#timeout a system call:
use Sys::SigAction qw( set_sig_handler );
eval {
my $h = set_sig_handler( 'ALRM' ,\&mysubname ,{ mask=>[ 'ALRM' ] ,safe=>1 } );
alarm(2)
... do something you want to timeout
alarm(0);
}; #signal handler is reset when $h goes out of scope
alarm(0);
if ( $@ ) ...
is buggy. Suppose the eval dies for some reason unrelated to the
signal handling just before the alarm expires, and then the code
exits the eval, and then the alarm expires before the final alarm(0)
can be called. Now either the code will completely die because
there is no SIGALRM handler in place to catch the signal, or the
wrong handler (not the local handler) will be called.
What you need instead is:
#timeout a system call:
use Sys::SigAction qw( set_sig_handler );
eval {
my $h = set_sig_handler( 'ALRM' ,\&mysubname ,{ mask=>[ 'ALRM' ] ,safe=>1 } );
eval {
alarm(2)
... do something you want to timeout
alarm(0);
};
alarm(0); # cancel alarm (if eval failed)
die $@ if $@;
}; #signal handler is reset when $h goes out of scope
if ( $@ ) ...
so the desired signal handler is called in this situation.
All of the code samples need to be reviewed for this problem.