Perl TimeOut

Problem

You have a script which runs too long and you want to time it out, after a given number
of seconds.



Solution

Useful bit of code to time-out a section of your Perl script, via the alarm function.

See the example tab.



Example



#!/usr/bin/perl

eval {

local %SIG;
$SIG{ALRM}=
sub{ die "timeout reached, after 20 seconds\n"; };
alarm 20;
print "sleeping for 60 secondsn";
sleep 60; # This is where to put your code, between the alarms
alarm 0;
};

alarm 0;

if([email protected]) { print "Error: [email protected]\n"; }

exit(0);


__END__



Reference

[tags]Perl timeout, Perl Coding School[/tags]



Comments (3)

  1. relin

    This can generate zombies ….

    like if we put a

    system (” ping hostname ” );

    the ping will be still running …

  2. mera naam

    You have left out the \ before the last n in your print statements, i.e. the print should end in a \n”; instead of the n”; shown above.

Leave a Reply

Your email address will not be published. Required fields are marked *