Skip to content
Browse files

add alarm code noblocking

  • Loading branch information...
1 parent 5c404d2 commit 998153153a54289bc2f5631d5469bef750d47343 @soarpenguin committed Dec 12, 2013
Showing with 15 additions and 0 deletions.
  1. +15 −0 demo.pl
View
15 demo.pl
@@ -81,3 +81,18 @@ ($)
}
sub realpath($) { return to_utf8(Cwd::realpath(@_)); }
sub bsd_glob($) { return map {to_utf8($_)} File::Glob::bsd_glob(@_); }
+
+# perform a code block and prevent it from blocking by using a timeout
+sub do_timeout($&)
+{
+ my ($seconds, $code) = @_;
+ local $SIG{ALRM} = sub {die "alarm clock restart executing $code"};
+ alarm $seconds; # schedule an alarm in a few seconds
+ eval {
+ &$code; # execute the code block or subroutine passed in
+ alarm 0; # cancel the alarm
+ };
+ if ($@ and $@ !~ /^alarm clock restart/) {die $@};
+} # noblock()
+
+do_timeout 10, sub { print "Hello, World!\n"};

0 comments on commit 9981531

Please sign in to comment.
Something went wrong with that request. Please try again.