A new-to-Perl user on alt.perl asked how to detect an infinite loop, having already been told to use something like setrlimit. Not wanting to scare the person off, I posted the following few lines as a cheap way to abort the Perl program after a timelimit goes off.

Caveats: doesn't work if the program uses eval or sleep, and might not work with retry I/O models. (But beginners aren't likely to use these things!)

BEGIN { $SIG{ALRM} = sub { die "Infinite loop aborted" }; alarm 30; # or however long you want before you time out (in seconds +) }

Replies are listed 'Best First'.
RE (tilly) 1: Poor man's setrlimit
by tilly (Archbishop) on Oct 16, 2000 at 18:41 UTC
    Very poor man's model you mean. It won't help if you do something like any of the following three lines:
    push @big, 1 while 1; $foo = $bar = "BIGBIG"; while ($foo =~ s/BIG/$bar/) {} sub oops {my $var = shift; oops($var);}
    I have seen all three mistakes made. In fact just yesterday I discovered an example of the third mistake in the 5.6.* implementation of Carp.pm. But you knew that. :-)
      What makes you think those won't be interrupted? alarm is a signals. Signals happen now. One of the discussions is to make signals "safe", meaning they wouldn't interrupt a Perl opcode, and your example is correct. But for now, they are dangerous, and poof! You be gone. {grin}

      -- Randal L. Schwartz, Perl hacker

        Um, 30 seconds is waaay longer than I would want to run one of those on a box with no limits and nothing in place to handle resource starvation gracefully...

        Trust me, I am not sitting at the counter now. This is one I have definitely been there on. :-(Why, tell me why, does Linux seem to think that klogd is a good target?)-: