#! /bin/sh
# with-timeout --- run process but kill if it hangs
# Author: Noah Friedman <friedman@splode.com>
# Created: 1996-05-26
# Public domain.

# $Id: with-timeout,v 1.4 2000/01/17 04:11:13 friedman Exp $

exec ${PERL-perl} -Sx $0 ${1+"$@"}
#!perl

sub spawn
{
  my $pid = fork;
  die if (!defined $pid);
  exec (@_) if ($pid == 0);
  return $pid;
}

sub sigalrm_handler
{
  printf (STDERR "with-timeout: @ARGV: Timeout waiting for process to complete.\n");
  kill (1, $proc);
  exit (1);
}

sub main
{
  if ($#ARGV < 1)
    {
      my $p = $0;
      $p =~ s|.*/||;
      print STDERR "Usage: $p [timeout] [command {args ...}]\n";
      exit (1);
    }

  $SIG{'ALRM'} = \&sigalrm_handler;
  alarm ($ARGV[0]);
  shift @ARGV;

  $proc = spawn (@ARGV);
  wait;
  exit ($?);
}

main();

# with-timeout ends here
