#!/usr/bin/env perl

use strict;

if (scalar(@ARGV) < 2) {
    print "ERROR: Usage: $0 <limit_seconds> <some command>\n\n";
    exit(101);
}

my $timeout = shift(@ARGV);
my @command = @ARGV;
my $time = time();

$SIG{ALRM} = \&Timeout;

alarm($timeout);
system(@command);
alarm(0);

# Analyze results
if ($? == -1) {
    print "ERROR: Failed to execute: $!\n";
    exit(102);
} elsif ($? & 127) {
    printf "ERROR: Child died with signal %d, %s coredump\n", ($? & 127),  ($? & 128) ? 'with' : 'without';
    exit(103);
}

exit($? >> 8);

#------------------------------
sub Timeout {
    print "ERROR: Execution timed out (" . (time() - $time) ." sec)!\n";
    exit(100);
}
