How do I get the output of Win32::Process command in Perl?
I am using use Win32::Process
for my application run as below. It runs fine, but I did not get any way to get the output to a .txt file.
I used NORMAL_PRIORITY_CLASS rather than CREATE_NEW_CONSOLE to get the output on the same terminal itself, but I don't know how to redirect it to a txt file.
/rocky
#!/usr/bin/perl
use strict;
use warnings;
use Win32::Process;
Win32::Process::Create(my $ProcessObj,
"iperf.exe",
"iperf.exe -u -s -p 5001",
0,
NORMAL_PRIORITY_CLASS,
".") || die ErrorReport();
my @command_output;
push @command_output,$ProcessObj;
open FILE, ">zz.txt" o开发者_StackOverflow中文版r die $!;
print FILE @command_output;
close FILE;
sleep 10;
$ProcessObj->Kill(0);
sub ErrorReport{
print Win32::FormatMessage( Win32::GetLastError() );
}
Win32::Process is one of those modules that's basically a straight port of the Win32 API into Perl and thus makes little sense to a Perl programmer. Unless you want to do something very Windows specific, there are better ways to do it.
If all you want is to get the output of a process, you can just run it normally using Perl's backticks.
my $output = `iperf.exe -u -s -p 5001`;
If you want to get fancy, for example backgrounding a process and capturing its output, I'd recommend IPC::Run.
You can achieve this using Win32::Process by redirecting STDOUT and STDERR to a text file.
use strict;
use warnings;
use File::Which qw(which);
use Win32;
use Win32::Process;
# Back up STDOUT and STDERR to OLDOUT and OLDERR
open (OLDOUT, ">&STDOUT");
open (OLDERR, ">&STDERR");
# Redirect STDOUT and STDERR to text file
my $file = "output.txt";
open (STDOUT, ">$file");
open (STDERR, ">&STDOUT");
# Create process
my $timeout = 60000 * 10; # 10 minute timeout
my ($process, $exitCode);
my $exe = which 'iperf';
Win32::Process::Create($process, $exe, "iperf.exe -u -s -p 5001", 1, 0, ".");
$process->Wait($timeout);
$process->GetExitCode($exitCode);
print "Spawned process exited with $exitCode\n";
# Restore STDOUT and STDERR
close (STDOUT);
close (STDERR);
open (STDOUT, ">&OLDOUT");
open (STDERR, ">&OLDERR");
close (OLDOUT);
close (OLDERR);
Note that in the Win32::Process::Create call, it is important to set $iflags and $cflags correctly (as in the example above) to ensure that the spawned process inherits the calling processes handles/console. The meanings of these flags can be found in the Win32::Process and Microsoft Windows documentation:
Win32::Process CPAN
Microsoft Windows process creation flags
From perlfaq8:
Backticks (``) run a command and return what it sent to STDOUT.
More details can be found in perlop.
精彩评论