Agnus Dei (jackal) wrote,
Agnus Dei
jackal

How to do timeouts in perl


#!/opt/local/bin/perl
$|++;

use strict;
my $timeout_length=3;  # 3 seconds

eval {
        local $SIG{ALRM} = sub { die "timeout\n" };
        alarm $timeout_length;
        infinite_loop();  # call the loop
        # print_line();  # print a single line
        alarm 0;
};

# warn "external command timed out: $@\n" if $@ eq "timeout\n"; # This only prints if the alarm timeout was hit.
if ( $@ eq "timeout\n") {
        warn "The timeout value was hit.... exiting....\n";
        exit 1;
}

sub infinite_loop {
        for( ; ; ) {
                printf "This loop will run forever.\n";
        }
}

sub print_line {
        print "Hello\n" ;
}
Subscribe
  • Post a new comment

    Error

    Anonymous comments are disabled in this journal

    default userpic

    Your reply will be screened

  • 0 comments