Skip to content

Instantly share code, notes, and snippets.

@memememomo
Created April 9, 2014 10:54
Show Gist options
  • Save memememomo/10254408 to your computer and use it in GitHub Desktop.
Save memememomo/10254408 to your computer and use it in GitHub Desktop.
Perlでタイムアウトを設定して外部コマンドを実行する ref: http://qiita.com/memememomo/items/72a10e1bbe04b57f5666
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