perlMunger has asked for the wisdom of the Perl Monks concerning the following question:

Here's my thought, I have a script that I want to monitor, if the script hangs for 20 minutes. The script will run from cron every 10 minutes. currently the script creates a lock file, so concurrent script (same script) can't run. Within this script, I would like to spawn a monitor (sub routine within script) that will kill the parent and itself, if the script hangs for 20 minutes and send a notification when it happens. Is this possible, with out having to write another monitor type script? TIA! PerlMunger
  • Comment on Monitor Perl script within the same script?

Replies are listed 'Best First'.
Re: Monitor Perl script within the same script?
by Animator (Hermit) on Dec 14, 2004 at 18:33 UTC
    I think you can use the alarm-function. (perldoc -f alarm)
      Animator, thanks for the help. After reading the docs (perldoc -f alarm), I still can't seem to figure out who to use it within a sub/function. Should I fork a process from the sub to monitor the parent? If so, do you have any suggestions that might help me with my quest. TIA! perlMunger
        It's been quite some time since I've written anything dealing with alarm but something like this may do what you need

        $SIG{ALRM} = sub { #cleanup lockfile #cleanup anything else exit; } alarm(1200); # do stuff # If you have system calls here (i.e. sysread) you # may need to do some wrapping with eval etc. (as per # the alarm perldoc alarm(0);
        This is untested. I think the approach will work, but as always, you mileage may vary. Update: time is in seconds not minutes.
Re: Monitor Perl script within the same script?
by mifflin (Curate) on Dec 15, 2004 at 16:37 UTC

    The perl Cookbook has a recipe on using alarm to solve your problem. See 16.22 if you have the book.

    Here is the code it uses
    $SIG{ALRM} = sub { die "timeout" }; eval { alarm(1200); # 20 minutes # long-time operations here alarm(0); }; if ($@) { if ($@ =~ /timeout/) { #timed out, do what you will here } else { die; # propagate the unexpected exception } }
Re: Monitor Perl script within the same script?
by perlMunger (Novice) on Dec 15, 2004 at 20:16 UTC
    I want to thank all that replied, the code (both) worked like a charm. Thanks again for the help. perlMunger