Skip to content

Instantly share code, notes, and snippets.

@cowens
Created July 14, 2009 04:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowens/146716 to your computer and use it in GitHub Desktop.
Save cowens/146716 to your computer and use it in GitHub Desktop.
A function to handle timing out
#!/usr/bin/perl
use strict;
use warnings;
sub timeout {
my ($wait, $code, $timedout, $error) = (@_,
sub { warn $@ }, sub { die $@ });
eval {
local $SIG{ALRM} = sub { die "timeout\n" };
alarm $wait;
$code->();
alarm 0;
1;
} or do {
alarm 0; #ensure that alarm is not still set
#raise error if it isn't a timeout
if ($@ eq "timeout\n") {
$timedout->();
} else {
$error->();
}
};
}
timeout 1,
sub { die "oops\n" },
sub { warn "timeout out\n" },
sub { warn "died with $@" };
timeout 1,
sub { select undef, undef, undef, 2 },
sub { warn "timeout out\n" },
sub { warn "died with $@" };
timeout 1,
sub { print "normal execution\n" },
sub { warn "timeout out\n" },
sub { warn "died with $@" };
timeout 1, sub { select undef, undef, undef, 2 };
timeout 1, sub { die "and here it ends" };
print "this is not printed\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment