Update: I have a simpler, cleaner version working now using
Win32::Job. I like this version a lot; note that it relies
on Windows 2000 and above.
use strict;
use Win32::Job;
select(STDERR);$|=1;select(STDOUT);$|=1; # autoflush
my $SysDir = "$ENV{SystemRoot}\\system32"; # is there a better way?
my $Outf = "out-$$.tmp";
my $Errf = "err-$$.tmp";
-f $Outf and (unlink($Outf) or die "error: unlink '$Outf': $!");
-f $Errf and (unlink($Errf) or die "error: unlink '$Errf': $!");
sub slurp_file {
my $file = shift;
local $/;
open(my $fh, $file) or die "error:open '$file': $!";
<$fh>;
}
sub write_result {
my ($pid, $rc, $elap, $user, $sys) = @_;
warn "pid=$pid, rc=$rc, elapsed=$elap user=$user sys=$sys\n";
my $outstr = slurp_file($Outf);
my $errstr = slurp_file($Errf);
unlink($Outf) or die "error: unlink '$Outf': $!";
unlink($Errf) or die "error: unlink '$Errf': $!";
warn "cmd stdout='$outstr'\n";
warn "cmd stderr='$errstr'\n";
}
# Run command $cmd, timing out after $timeout seconds.
sub run_for {
my ($cmd, $timeout) = @_;
warn "run $cmd->[0] ($cmd->[1]) at " . scalar(localtime) . "\n";
my $job = Win32::Job->new();
defined($job) or die "error creating job: $^E";
my $pid = $job->spawn($cmd->[0], $cmd->[1],
{ stdin => 'NUL', stdout => $Outf, stderr => $Errf } )
or die "error spawn: $^E";
warn "in run_for, waiting for pid=$pid\n";
$job->run($timeout);
my $stat = $job->status();
exists($stat->{$pid}) or die "oops, no status for $pid";
my $rc = $stat->{$pid}->{exitcode};
my $t = $stat->{$pid}->{time};
write_result($pid, $rc, $t->{elapsed}, $t->{user}, $t->{kernel});
}
my @cmds = (
[ "$SysDir\\netstat.exe", 'netstat -na' ],
[ $^X, 'perl -e "print STDERR Hello;sleep 15"' ],
[ $^X, 'perl -e "print STDERR World"' ],
[ "$SysDir\\cmd.exe", 'cmd /c DIR' ],
);
for my $cmd (@cmds) {
run_for($cmd, 10);
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.