Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Comment on

( #3333=superdoc: print w/replies, xml ) Need Help??

I want to run a series of Unix commands -- killing them if they take too long -- and timing how long each command takes to run. Below is my first attempt. It is very easy to have subtle bugs in these sorts of programs, so I would appreciate any advice on how to improve the code below.

use strict; use warnings; use POSIX ":sys_wait_h"; use Time::HiRes qw(time sleep); use Benchmark; # use Benchmark ':hireswallclock'; # 5.8 and above select(STDERR);$|=1;select(STDOUT);$|=1; # autoflush sub slurp_file { my $file = shift; local $/; open(my $fh, $file) or die "error:open '$file': $!"; <$fh>; } my $Pid; my $Outf = "out-$$.tmp"; my $Errf = "err-$$.tmp"; sub write_result { my ($killsig, $elap, $user, $sys) = @_; my $rc = $? >> 8; # return code of command my $sig = $? & 127; # signal it was killed with warn "pid=$Pid, rc=$rc sig=$sig (killsig=$killsig)\n"; warn " elapsed=$elap user=$user sys=$sys\n" if defined($elap); 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"; } sub run_cmd { my $cmd = shift; warn "\nrun_cmd '$cmd' at " . scalar(localtime) . "\n"; my $b0 = Benchmark->new(); my $t0 = time(); defined($Pid = fork()) or die "error: fork: $!"; if ($Pid == 0) { ### child open(STDOUT, '>'.$Outf) or die "error create '$Outf': $!"; open(STDERR, '>'.$Errf) or die "error create '$Errf': $!"; exec($cmd); # my @args = split(' ', $cmd); exec { $args[0] } @args; die "error: exec: $!"; } ### parent warn "in run_cmd, waiting for pid=$Pid\n"; waitpid($Pid, 0); my $t1 = time(); my $b1 = Benchmark->new(); my $bd = timediff($b1, $b0); my ($real, $child_user, $child_sys) = @$bd[0,3,4]; write_result(0, $t1 - $t0, $child_user, $child_sys); } # Run command $cmd, timing out after $timeout seconds. # See Perl Cookbook 2nd edition, Recipe 16.21 # See also perlfaq8 "How do I timeout a slow event". # Return 1 if $cmd run ok, 0 if timed out. sub run_for { my ($cmd, $timeout) = @_; my $diestr = 0; eval { local $SIG{ALRM} = sub { die "alarm clock restart" }; alarm($timeout); # schedule alarm in $timeout seconds eval { run_cmd($cmd) }; $diestr = $@ if $@; alarm(0); # cancel the alarm }; $diestr = $@ if $@; alarm(0); # race condition protection return 1 unless $diestr; return 0 if $diestr =~ /alarm clock restart/; die; } sub kill_it { warn "kill_it: pid=$Pid\n"; kill(0, $Pid) or warn("pid $Pid is not alive\n"), return; my $waitpid; my $killsig = 15; kill($killsig, $Pid); sleep(0.1); for (1..3) { $waitpid = waitpid($Pid, &WNOHANG); last if $waitpid == $Pid; sleep(1); } if ($waitpid != $Pid && kill(0, $Pid)) { $killsig = 9; warn "pid $Pid not responding, resorting to kill 9\n"; kill($killsig, $Pid); waitpid($Pid, 0); } write_result($killsig); } my @cmds = ( 'ls -l', 'sleep 15', 'sleep 4', 'echo hello-stdout; echo hello-stderr >&2', ); for my $cmd (@cmds) { run_for($cmd, 10) or kill_it() }

Update: see also Timing Windows commands.

In reply to Timing and timing out Unix commands by eyepopslikeamosquito

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and all is quiet...

    How do I use this? | Other CB clients
    Other Users?
    Others musing on the Monastery: (2)
    As of 2018-04-25 01:35 GMT
    Find Nodes?
      Voting Booth?