Skip to content

Commit 9981531

Browse files
committed
add alarm code noblocking
1 parent 5c404d2 commit 9981531

File tree

1 file changed

+15
-0
lines changed

1 file changed

+15
-0
lines changed

Diff for: demo.pl

+15
Original file line numberDiff line numberDiff line change
@@ -81,3 +81,18 @@ ($)
8181
}
8282
sub realpath($) { return to_utf8(Cwd::realpath(@_)); }
8383
sub bsd_glob($) { return map {to_utf8($_)} File::Glob::bsd_glob(@_); }
84+
85+
# perform a code block and prevent it from blocking by using a timeout
86+
sub do_timeout($&)
87+
{
88+
my ($seconds, $code) = @_;
89+
local $SIG{ALRM} = sub {die "alarm clock restart executing $code"};
90+
alarm $seconds; # schedule an alarm in a few seconds
91+
eval {
92+
&$code; # execute the code block or subroutine passed in
93+
alarm 0; # cancel the alarm
94+
};
95+
if ($@ and $@ !~ /^alarm clock restart/) {die $@};
96+
} # noblock()
97+
98+
do_timeout 10, sub { print "Hello, World!\n"};

0 commit comments

Comments
 (0)