简体   繁体   English

在Perl中使用系统cmd时超时

[英]Time out when using system cmd in perl

I'm using PSEXEC to run remote process with system($CMD) in perl. 我正在使用PSEXEC在perl中使用system($CMD)运行远程进程。

I have a computer (lets call it-#1) that runs system cmd , and another computer (lets call it-#2), which "receives" commands from computer #1. 我有一台运行system cmd的计算机(让我们称它为#1),另一台计算机(让它称它为#2),可以“接收”来自计算机#1的命令。

Sometimes the process in the second computer (#2) gets stuck. 有时第二台计算机(#2)中的进程卡住了。

How can I set a timeout to the system cmd in computer #1 that will force-terminate the cmd after several minutes? 如何在计算机#1中的系统cmd设置超时,该超时将在几分钟后强制终止cmd?


thanks for the answers, but: i'm tring to do somthing very simple, I have 2 perl files. 感谢您的回答,但是:我非常想做些简单的事情,我有2个perl文件。 file#1 that counting seconds 1 to 10. (+print to the screen) file#2-Timeout file that cal file#1 (system command) that should terminate file #1 after 5 sec. 记录秒1到10的文件#1(+打印到屏幕)。文件#2-超时文件,该文件应在5秒后终止文件#1的文件#1(系统命令)。

the results...: timeout occurred, but process #1 still running... 结果...:发生超时,但是进程#1仍在运行...

file#2 文件#2

$timeout=5;
eval {
    local $SIG{ALRM} = sub { die "alarm\n" }; # NB: \n required
    alarm $timeout;
    $nread = system('F:\perl1.pl');
    alarm 0;
};
if ($@) {
    die unless $@ eq "alarm\n";   # propagate unexpected errors
    print "process terminated\n";}
else {
    # didn't
}

file#1 文件#1

$i=0;
while($

    i<10){
    sleep(1);
    $i++;

print "$i\n";
}

CMD window results: CMD窗口结果:

C:\>F:\perl2.pl
1
2
3
4
process terminated

C:\>5
6
7
8
9
10

Let IPC::Run handle that for you. IPC :: Run为您处理。

use IPC::Run qw( run timeout );

run \@cmd, timeout( 120 )
   or die "cat: $?";

You could use alarm in your situation: 您可以根据情况使用alarm

If you want to use alarm to time out a system call you need to use an eval / die pair. 如果要使用alarm使system调用超时,则需要使用eval / die对。 You can't rely on the alarm causing the system call to fail with $! 您不能依靠导致$!的系统调用失败的alarm $! set to EINTR because Perl sets up signal handlers to restart system calls on some systems. 设置为EINTR是因为Perl设置了信号处理程序以在某些系统上重新启动system调用。 Using eval / die always works, modulo the caveats given in Signals in perlipc . 使用eval / die始终有效, perlipc中的Signals中给出的警告为模。

 eval { local $SIG{ALRM} = sub { die "alarm\\n" }; # NB: \\n required alarm $timeout; $nread = sysread SOCKET, $buffer, $size; alarm 0; }; if ($@) { die unless $@ eq "alarm\\n"; # propagate unexpected errors # timed out } else { # didn't } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM