#!/usr/bin/env perl
# 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.6 2006/11/29 04:55:05 friedman Exp $

$^W = 1;  # enable warnings

use strict;

(my $progname = $0) =~ s|.*/||;

sub fatal
{
  print STDERR join (": ", $progname, @_), "\n";
  exit (1);
}

sub spawn
{
  my $pid = fork;
  fatal ("fork", "$!") unless defined $pid;
  return $pid if $pid > 0;
  exec (@_) || fatal ("exec", $_[0], "$!");
}

sub main
{
  unless (@ARGV)
    {
      print STDERR "Usage: $progname [timeout] [command {args ...}]\n";
      exit (1);
    }

  my $timeout = shift @ARGV;
  my $proc;

  $SIG{ALRM} = sub
    {
      kill (1, $proc);
      fatal ($ARGV[0], "Timeout waiting $timeout seconds for process to complete.");
    };

  alarm ($timeout);
  $proc = spawn (@ARGV);
  wait if $proc;
  return $?;
}

main;

# with-timeout ends here
