in reply to brutally stop a perl program if it runs too long

There are several ways to do it.

Since you want something standalone, without ties to the caller, a seperate process seems best. That allows the parent to use any timers and alarms it likes.

Lets call the thing "Timelimit", and abuse import to set the limit and fork, per Errto.

package Timelimit; use warnings; use strict; =head1 NAME Timelimit - fork off a watchdog timer =cut =head1 SYNOPSIS use Timelimit $seconds; use Timelimit; # default 120 seconds =cut use vars qw/$N/; sub import { my $class = shift; $N = 0+$_[0] || 120; # default two minutes my $ppid = $$; defined(my $pid = fork) or die $!; return $pid if $pid; local $SIG{HUP} = sub { exit 0 }; while ($N > 0) { $N -= sleep $N; } kill INT, $ppid; # or, for maximum brutality, # kill KILL, $ppid; sleep 1 while kill 0, $ppid; exit 0; } 1; __END__ =head1 AUTHOR Zaxo, Sept 2005 =cut
The initial $Timelimit::N setting is visible to the user who wants to see it.

Update ++Errto's suggestion gratefully adopted.

After Compline,
Zaxo

Replies are listed 'Best First'.
Re^2: brutally stop a perl program if it runs too long
by Errto (Vicar) on Sep 13, 2005 at 03:18 UTC
    Cool idea, but I don't think it works as is (at least not for me) because the import routine is called after the module is required, so the forking block would never see the correct value of $N. The solution is simply to make it all part of the import subroutine, and use return instead of last.