Created
April 9, 2014 10:54
-
-
Save memememomo/10254408 to your computer and use it in GitHub Desktop.
Perlでタイムアウトを設定して外部コマンドを実行する ref: http://qiita.com/memememomo/items/72a10e1bbe04b57f5666
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use POSIX qw( SIGKILL ); | |
my $TIMEOUT = 10; | |
my $cmd = "sleep 15"; | |
my $pid = fork(); | |
if (!defined($pid)) { die "failed to fork"; } | |
if ($pid == 0) { | |
exec($cmd); | |
exit; | |
} | |
elsif ($pid) { | |
my $timeout = 0; | |
eval { | |
local $SIG{ALRM} = sub { | |
$timeout = 1; | |
}; | |
alarm($TIMEOUT); | |
while(!$timeout) { | |
last if waitpid($pid, POSIX::WNOHANG); | |
sleep(1); | |
} | |
}; | |
if ($@) { | |
warn "Error:".$@; | |
} | |
if ($timeout) { | |
kill(SIGKILL, $pid); | |
warn "TIMEOUT"; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment