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

hi is there any perl module to timeout a particular proceess? for example there is an infinite loop as below
for($i=1;;$i++) { print "hi"; }
Is there any module in perl to timeout say in 2 seconds without looping indefinitly ? Any help will be apreciated. Thanks in advance.

Replies are listed 'Best First'.
Re: Timing out
by ikegami (Patriarch) on Feb 10, 2010 at 08:17 UTC

    If you need something a bit more forceful and more reliable than alarm*, you could fork the work off to a child and kill the child if it takes too long to respond.

    * — alarm won't interrupt a very long pattern match or XS function call, for example. See the documentation on safe signals in perlipc.

Re: Timing out
by 7stud (Deacon) on Feb 10, 2010 at 08:13 UTC
    • eval() block, $@, die() <=> try, catch, throw
    • signals
    • alarm()
    use strict; use warnings; use 5.010; eval { local $SIG{ALRM} = sub {die "my timeout"}; #execute this sub when ALRM signal received alarm 3; #sends ALRM signal to this process in 3 secs, which causes sub #to execute $| = 1; #turn off buffering to STDOUT, otherwise all output will come at #program termination when STDOUT's buffer is automatically #flushed while (1) { say 'hi'; sleep 1; } }; #<-- don't forget that semi-colon --output:-- hi hi hi

    "Throwing" the error with die() will cause execution to jump out of the eval() block. After the eval() block terminates, the die() message is available in $@. If the eval block terminates without error, $@ will be the null string(whatever that is).

Re: Timing out
by Anonymous Monk on Feb 10, 2010 at 07:42 UTC