perl - 终止在 Perl 中使用 system() 启动的应用程序

标签 perl

我正在尝试使用 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/

相关文章:

linux - 使用正则表达式对文件运行 awk

linux - 如果使用相同 IP/端口的连接断开,则 Shell 脚本警报

perl - 移动/克隆 perlbrew 安装的 perl 以及所有额外的 cpan 模块

xml - 如何使用 Perl 查找和替换 XML 中的文本?

mysql - 将Mysql存储的数据转换为正确的utf8

perl - 如何使用任意外部程序作为 perl 程序中的过滤器?

perl - 如何在程序执行中保持标量值?

regex - 如何在 Perl 中使用 REGEX 查找字符串中的第 n 个字符或数字

perl - 为什么 Hadoop Streaming 找不到我的脚本?

perl - 如何全局声明一个变量,使其对所有 perl 模块都可见?