[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Omaha.pm] Alarms in Perl.



On Oct 25, 2007, at 11:08 AM, Daniel Linder wrote:
What I would like to setup is a simple alarm based action that would exit the script -- no matter what -- if it was still running after an extended
period of time.

Your example seems overly complicated to me. I think all you need is $SIG{ALRM} and alarm().

$ cat j.pl
local $SIG{ALRM} = \&timeout;
alarm(5);

sleep 10;   # My "long_running_code()"
print "I did not time out. \n";
exit;

sub timeout {
   print "Timed out\n";
   exit;
}

$ perl j.pl
Timed out


That said, I'll take a stab at your questions...

1: Will (should) this work even if the "long_running_code()" uses system()
and or back-ticks to call out to external programs?  (I realize those
programs could be left running - I'm ok with having the admin clean them
up once they are alerted to the code not returning at all...)

... I haven't studied Object::Destroyer, but it's probably a safe bet that all children process will terminate when your parent process (your Perl program) does.

2: Are the alarm() and Object::Destroyer calls part of the base Perl
modules, or will I be visiting CPAN to get this working? (How do I check
what's included out of the box vs. what has been installed over time?)

You should be able to see what has been installed after Perl via:

perldoc perllocal

3: Is there any command-line magic that perl can be invoked with that will cause Perl to call a specific function if it is left running for a long
period of time?  (i.e. perl --timeout 300 --timeout-sub
'MyExitSubroutine()' ./MyBigPerlScript.pl)

Whatever you set $SIG{ALRM} to is what will get called if the kernel sends the ALRM signal.

I wouldn't think you would want that to be based on a command-line argument, but if you did maybe you could try something like:

   $SIG{ALRM} = eval{ "\&$ARGV[0]" };

My favorite way of handling --timeout-sub args is via Getopt::Long. It's groovy.

HTH,

j