summaryrefslogtreecommitdiff
path: root/Tools/portbuild/scripts/ptimeout
blob: 53e28b77c3aeace599ba6c80ed2ac6e7448181d9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/perl -w
# ptimeout: executes command but kills it after a specified timeout
# usage: ptimeout timeout command args ...
$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\n";
    kill 'TERM', $pid1;
    exit 1;
  }
}
else {
  # first child
  print "executing @ARGV\n";
  exec @ARGV;
}