6

I'm running a command line application from within the perl script(using system()) that sometimes doesn't return, to be precise it throws exception which requires the user input to abort the application. This script is used for automated testing of the application I'm running using the system() command. Since, it is a part of automated testing, sytem() command has to return if the exception occurs and consider the test to be fail.

I want to write a piece of code that runs this application and if exception occurs it has to continue with the script considering the this test to be failed.

One way to do this is to run the application for certain period of time and if the system call doesn't return in that period of time we should terminate the system() and continue with the script. (How can I terminate a system command with alarm in Perl?)

code for achieving this:

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
}

but this code doesn't work on windows i did some research on this and found out that SIG doesn't work for windows(book programming Perl). could some one suggest how could I achieve this in windows?

Community
  • 1
  • 1
int80h
  • 265
  • 1
  • 3
  • 12

2 Answers2

7

I would recommend looking at the Win32::Process module. It allows you to start a process, wait on it for some variable amount of time, and even kill it if necessary. Based on the example the documentation provides, it looks quite easy:

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
}

You could also sleep for the appropriate number of seconds and use the kill method in this module. I'm not exactly sure if the NORMAL_PRIORITY_CLASS creation flag is the one you want to use; the documentation for this module is pretty bad. I see some examples using the DETACHED_PROCESS flag. You'll have to play around with that part to see what works.

Jonah Bishop
  • 12,279
  • 6
  • 49
  • 74
2

See Proc::Background, it abstracts the code for both win32 and linux, the function is timeout_system( $seconds, $command, $arg, $arg, $arg )