Subject: | Signal-handling sample code is buggy |
Date: | Sun, 18 Oct 2009 12:50:04 -0700 (PDT) |
To: | bug-DBI [...] rt.cpan.org |
From: | eponymous alias <eponymousalias [...] yahoo.com> |
The example code for signal handling:
eval {
local $SIG{ALRM} = sub { die "TIMEOUT\n" };
alarm($seconds);
... code to execute with timeout here ...
alarm(0); # cancel alarm (if code ran fast)
};
alarm(0); # cancel alarm (if eval failed)
if ( $@ eq "TIMEOUT\n" ) { ... }
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 $SIG{ALRM} handler in place to catch the signal, or
the wrong handler (not the local handler) will be called.
What you need instead is:
eval {
local $SIG{ALRM} = sub { die "TIMEOUT\n" };
eval {
alarm($seconds);
... code to execute with timeout here ...
alarm(0); # cancel alarm (if code ran fast)
};
alarm(0); # cancel alarm (if eval failed)
die $@ if $@;
};
if ( $@ eq "TIMEOUT\n" ) { ... }
so the desired signal handler is called in this situation.
The same problem affects the sample sigaction code just below
this timeout example.