11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Perlでタイムアウトを設定して外部コマンドを実行する

Last updated at Posted at 2014-04-09

fork + exec + alarm で、以下のようにやった。

sample.pl
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";
    }
}
11
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?