/*        
timeout.c v.0.2: execute command handling timeout
condition. If no commands are specified, it wait
for a key pressed.
Syntax:

		# timeout seconds
or
		# timeout seconds "cmd arg1 arg2 ..."		


(C)1999-2000 M. Andreoli	

 */

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

void alarm_signal(int);

char key[5];
int to;
Char **cmd;
int pid=0,status;

main(int argc, char **argv)
{
/* syntax */
if (argv[1] == NULL )
{
fprintf(stderr,"Usage: timeout [seconds] [command args ...]\n");
exit(1);
}
to=atoi(argv[1]); /* seconds to wait */
if (argv[2] != NULL )
	cmd=argv+2;
else
	cmd=(char**) 0;

/* install signal handler */
signal(SIGALRM,alarm_signal);

printf(" comando da ex [%s]\n",cmd[0]);
/* set alarm() */
alarm(0);
alarm(to);

if ( cmd[0] == NULL ) {
	/* called with a single timeout argument */
	read(0,key,1);
	exit(1);
}  else {
	/* execv(cmd[0],cmd); */
	system(cmd[0]);
}


}

void alarm_signal(int sig)
{
fprintf(stderr,"timeout\n");
if ( pid!=0) kill(pid,SIGKILL);
exit(0);
}
