#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <ctype.h>
#include <signal.h>

int killed = 0;

void welcometotheworld (int discarded) {
	exit (killed);
}

int main (int argc, char * * argv) {
	int pid;
	char * p;
	unsigned long tix;

	if (argc < 3) {
		printf ("%s time command\nI send SIGKILL to command if not finished in time\n", * argv);
		printf ("time is seconds, or milliseconds if suffixed m or ms\n");
		printf ("exits with 0 if process exits normally, 1 if SIGKILLed, other if command is broken\n");
		exit (2);
	}
	p = argv[1];
	if (! isdigit (*p)) {
		printf ("Inappropriate time value \"%s\"\n", p);
		exit (2);
	}
	tix = strtoul (p, & p, 10);
	if (tix == 0 || p == argv [1]) {
		printf ("Unable to decipher time value \"%s\"\n", argv [1]);
		exit (2);
	}
	if (*p == 'm' || *p == 'M')
		tix *= 1000UL;
	else
		tix *= 1000000UL;
	signal (SIGCHLD, welcometotheworld);
	pid = fork ();
	if (pid) {
		usleep (tix);
		killed = 1;
		kill (pid, SIGKILL);
		printf ("%s: timeout\n", * argv);
		exit (1);
	}
	execvp (argv [2], argv + 2);
	exit (3);
}

