[英]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 asystem
call you need to use aneval
/die
pair.如果要使用
alarm
使system
调用超时,则需要使用eval
/die
对。 You can't rely on thealarm
causing the system call to fail with$!
您不能依靠导致
$!
的系统调用失败的alarm
$!
set toEINTR
because Perl sets up signal handlers to restartsystem
calls on some systems.设置为
EINTR
是因为Perl设置了信号处理程序以在某些系统上重新启动system
调用。 Usingeval
/die
always works, modulo the caveats given in Signals inperlipc
.使用
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.