在Windows中经过一段时间后终止系统()

int*_*80h 5 perl

我正在运行perl脚本中的命令行应用程序(使用system()),有时候不返回,确切地说它抛出异常,需要用户输入才能中止应用程序.此脚本用于使用system()命令自动测试我正在运行的应用程序.因为它是自动化测试的一部分,所以如果发生异常,sytem()命令必须返回并认为测试失败.

我想编写一段运行此应用程序的代码,如果发生异常,则必须继续使用脚本,因为此测试失败了.

一种方法是运行应用程序一段时间,如果系统调用没有在那段时间内返回,我们应该终止system()并继续脚本.(如何在Perl中终止带有警报的系统命令?)

实现此目的的代码:

my @output;
eval {
    local $SIG{ALRM} = sub { die "Timeout\n" };
    alarm 60;
    return = system("testapp.exe");
    alarm 0;
};
if ($@) {
    print "Test Failed";
} else {
    #compare the returned value with expected
}
Run Code Online (Sandbox Code Playgroud)

但是这段代码在windows上不起作用我对此做了一些研究,发现SIG不能用于windows(书籍编程Perl).有人可能会建议我如何在Windows中实现这一目标?

Jon*_*hop 6

我建议看一下Win32 :: Process模块.它允许您启动一个进程,等待一段可变的时间,甚至在必要时将其终止.根据文档提供的示例,它看起来很容易:

use Win32::Process;
use Win32;

sub ErrorReport{
    print Win32::FormatMessage( Win32::GetLastError() );
}

Win32::Process::Create($ProcessObj,
                       "C:\\path\\to\\testapp.exe",
                       "",
                       0,
                       NORMAL_PRIORITY_CLASS,
                       ".")|| die ErrorReport();

if($ProcessObj->Wait(60000)) # Timeout is in milliseconds
{
    # Wait succeeded (process completed within the timeout value)
}
else
{
    # Timeout expired. $! is set to WAIT_FAILED in this case
}
Run Code Online (Sandbox Code Playgroud)

您也可以睡眠适当的秒数并使用kill此模块中的方法.我不确定NORMAL_PRIORITY_CLASS创建标志是否是您要使用的标志; 这个模块的文档非常糟糕.我看到一些使用DETACHED_PROCESS旗帜的例子.你将不得不玩这个部分,看看有什么作用.