Perl 外部コマンド実行中にタイムアウトで終了させたい
ループ回しながら動的に引数作って外部コマンドを実行させつつ、遅いのはタイムアウトさせたい。
こんなかんじ?
#!/usr/bin/env perl use strict; use warnings; use IPC::Open3 qw/open3/; my $command; my $timeout = 3; foreach (0..3) { $command = "sleep $_; echo $_"; print join '', _exec($command); } sub _exec { my $command = shift; my @res; my $pid; eval{ local $SIG{ALRM} = sub { die "pid:$pid ($command) is timeout\n" }; alarm $timeout; my ( $writer, $reader ); $pid = open3( $writer, $reader, 0, $command ); close $writer; @res = <$reader>; waitpid($pid, 0); alarm 0; }; if ($@) { warn $@; kill("TERM", $pid) if $pid; return; } return @res; } % perl open3.pl 0 1 2 pid:20662 (sleep 3; echo 3) is timeout
参考
alarm - perldoc.perl.org
IPC::Open3 の正しい使い方 (re .pl な config ファイルのコンパイルがとおるかチェックしてみる - TokuLog 改メ tokuhirom’s blog) - kazuhoのメモ置き場