#!/usr/bin/perl -w
# ptimeout: executes command but kills it after a specified timeout
# usage: ptimeout timeout command args ...

require "ctime.pl";

$timeout=$ARGV[0];
splice(@ARGV, 0, 1);
#print "timeout is ", $timeout, "\n";
#print "arguments are ", "@ARGV", "\n";
if ($pid1 = fork) {
  if ($pid2 = fork) {
    # parent
    #print 'child pids are ', $pid1, ' ', $pid2, "\n";
    $child=wait;
    $status=$?;
    #print "exited child is $child, status is $status\n";
    if ($pid1 = $child) {
      #print "killing process $pid2\n";
      kill 'TERM', $pid2;
    }
    else {
      #print "killing process $pid1\n";
      kill 'TERM', $pid1;
    }
    # exit status in upper 8 bits, killed signal (if any) in lower 8 bits
    exit (($status >> 8) | ($status & 0xff)) ;
  }
  else {
    # second child
    sleep $timeout;
    print "ptimeout: killing @ARGV (pid $pid1) since timeout of $timeout expired at ", &ctime(time);
    kill 'TERM', $pid1;
    exit 1;
  }
}
else {
  # first child
  #print "executing @ARGV\n";
  exec @ARGV;
}
