我正在尝试使用 system()
在 Perl 脚本内运行应用程序。我正在运行的应用程序有时会卡住(它进入某种无限循环)。有没有办法让我知道这个应用程序是否卡住并终止它以继续执行 Perl 脚本?
我正在尝试做这样的事情:
start testapp.exe;
if(stuck with testapp.exe) {
kill testapp.exe;
}
最佳答案
判断是否“陷入无限循环”调用Halting Problem并且是不可判定的。
如果您想终止它,则必须使用 fork
fork 该应用程序,然后从另一个 fork 中终止它(如果该应用程序运行时间太长)。
您可以通过此确定该过程是否持续太长
use POSIX ":sys_wait_h";
waitpid($pid, WNOHANG)>0 #waitpid returns 0 if it still running
至少,根据this manual page
我不确定它在各种系统上的效果如何,你可以尝试一下。
不是直接答案,但如果您想轻松 fork ,我可以建议使用 forks
模块,但它仅在 UNIX 系统上工作(不能 窗口)。
好的,更多帮助代码:)它在 UNIX 中工作,根据 perlfork perldoc,它在 Windows 上应该以完全相同的方式工作。
use warnings;
use strict;
use POSIX ":sys_wait_h";
my $exited_cleanly; #to this variable I will save the info about exiting
my $pid = fork;
if (!$pid) {
system("anything_long.exe"); #your long program
} else {
sleep 10; #wait 10 seconds (can be longer)
my $result = waitpid(-1, WNOHANG); #here will be the result
if ($result==0) { #system is still running
$exited_cleanly = 0; #I already know I had to kill it
kill('TERM', $pid); #kill it with TERM ("cleaner") first
sleep(1); #wait a bit if it ends
my $result_term = waitpid(-1, WNOHANG);
#did it end?
if ($result_term == 0) { #if it still didnt...
kill('KILL', $pid); #kill it with full force!
}
} else {
$exited_cleanly = 1; #it exited cleanly
}
}
#you can now say something to the user, for example
if (!$exited_cleanly) {...}
关于perl - 终止在 Perl 中使用 system() 启动的应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8468991/