在Windows中经过一段时间后终止系统()
问题描述:
我在perl脚本中运行了一个命令行应用程序(使用system()),它有时不会返回,确切地说它会抛出需要用户输入以中止应用程序。该脚本用于使用system()命令运行的应用程序的自动化测试。因为它是自动化测试的一部分,所以如果发生异常,则必须返回sytem()命令并认为测试失败。在Windows中经过一段时间后终止系统()
我想编写一段运行此应用程序的代码,并且如果发生异常,则必须继续考虑此测试失败的脚本。
执行此操作的一种方法是在某段时间内运行应用程序,如果系统调用在该时间段内未返回,则应终止系统()并继续执行脚本。为实现这一 (How can I terminate a system command with alarm in Perl?)
代码:
my @output;
eval {
local $SIG{ALRM} = sub { die "Timeout\n" };
alarm 60;
return = system("testapp.exe");
alarm 0;
};
if ([email protected]) {
print "Test Failed";
} else {
#compare the returned value with expected
}
但是这个代码不工作在Windows上我做了一些这方面的研究和发现,SIG不会对窗口工作(书的Perl编程)。 可能有人建议我怎么能在Windows中实现这一点?
答
我会建议看看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
}
您还可以睡上几秒钟的适当数量而这个模块中使用kill
方法。我不确定NORMAL_PRIORITY_CLASS
创建标志是否是您想要使用的标志;该模块的文档非常糟糕。我看到一些使用DETACHED_PROCESS
标志的例子。你将不得不玩弄那部分看看有什么作用。
非常感谢!有用 :) – int80h 2012-01-30 02:52:16