Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

Re: Timing Windows commands

by eyepopslikeamosquito (Archbishop)
on Feb 03, 2004 at 05:36 UTC ( [id://326118]=note: print w/replies, xml ) Need Help??


in reply to Timing Windows commands

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); }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://326118]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others cooling their heels in the Monastery: (7)
As of 2024-03-28 21:03 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found