Alarm has only recently been implemented on Win32, and it still seems to have some limitations.
Here's another way of achieving this that should be portable back to at least 5.6.1.
#! perl -slw
use strict;
sub systemWithTimeout {
my( $timeout, $command ) = @_;
my $pid = open my $in, "$command |" or die $!;
my $endtime = time() + $timeout;
Win32::Sleep 100 while time() < $endtime and kill 0, $pid;
Win32::Sleep 0; ## Give the other process a timeslot to go away
my $wasKilled = kill 9, $pid if kill 0, $pid;
return wantarray ? ( $wasKilled , <$in> ): $wasKilled;
}
for ( 4 .. 6 ) {
print "5 second timeout on a process that runs for $_ seconds";
my( $timeout, @results ) = systemWithTimeout 5,
qq[ perl -wle" sleep $_; print $$, ' ', scalar localtime;" ];
printf "The process %s timeout\n", $timeout ? 'did' : 'did not';
print "it returned\n @results" if @results;
}
print "\nscalar context";
if( systemWithTimeout 5, qq[ perl -wle" sleep 3; print for 1 .. 100" ]
+ ) {
print "command timed out";
}
else {
print "command completed";
}
if( systemWithTimeout 5, qq[ perl -wle" sleep 7; print for 1 .. 100" ]
+ ) {
print "command timed out";
}
else {
print "command completed";
}
__END__
C:\test>539889
5 second timeout on a process that runs for 4 seconds
The process did not timeout
it returned
1896 Wed Mar 29 11:50:25 2006
5 second timeout on a process that runs for 5 seconds
The process did not timeout
it returned
1896 Wed Mar 29 11:50:31 2006
5 second timeout on a process that runs for 6 seconds
The process did timeout
scalar context
command completed
command timed out
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
|