Perl:为通过反引号调用的进程实现超时(和终止)



我正在尝试实现一个例程,该例程将接受"命令"和关联的"超时"。如果命令在指定时间内完成,则应返回输出。否则 - 它应该杀死这个过程。

sub runWithTimeout {
   my ($pCommand,$pTimeOut) = @_;
   my (@aResult);
   print "Executing command [$pCommand] with timeout [$pTimeOut] sec/s n";
   eval {
        local $SIG{ALRM} = sub { die "alarmn" };
        alarm $pTimeOut;
        @aResult = `$pCommand`;
        alarm 0;
   };
   if ($@) {
        print("Command [$pCommand] timed outn");
        # Need to kill the process.However I don't have the PID here.
        # kill -9 pid
    } else {
        print "Command completedn";
        #print Dumper(@aResult);
    }
}

示例调用:

&runWithTimeout('ls -lrt',5);
Executing command [ls -lrt] with timeout [5] sec/s 
Command completed

&runWithTimeout('sleep 10;ls -lrt',5);
Executing command [sleep 10;ls -lrt] with timeout [5] sec/s 
Command [sleep 10;ls -lrt] timed out

猜我是否随身携带 PID - 我可以在 if 块中的 PID 上使用"杀死"。

任何关于如何获得PID(或任何其他更好的方法)的指针 - 这将是一个很大的帮助。

不要使用反引号运行命令,而改用open。对于奖励积分 - 使用 IO::Selectcan_read 查看您是否有任何输出:

use IO::Select; 
my $pid = open ( my $output_fh, '-|', 'ls -lrt' );
my $select = IO::Select -> new ( $output_fh ); 
while ( $select -> can_read ( 5 ) ) { 
    my $line = <$output_fh>;
    print "GOT: $line"; 
}
##timed out after 5s waiting.  
kill 15, $pid;

最新更新