#!/bin/csh -f
#
# inputs:
#	$1 name of process to time
#	$2 number of seconds to allow process to run
#

if ($#argv < 2) then
    	echo "usage: $0 process_name seconds"
	exit
endif

# ignore ^C
onintr -

#
# wait until process started
#
set stpid = ()
while ($#stpid == 0)
    set stpid = `ps -aux | grep $1 | grep -v grep | grep -v timer | awk '{print $2}'`
end

if ($#stpid != 1) then
	echo ""$0": more than 1 process called $1" > /dev/console
	exit(1)
endif

@ start_time = `gettime`
@ end_time = $start_time + $2

while (`gettime` < $end_time)
        sleep 10
	# see if the process was terminated
	kill -0 $stpid >& /dev/null
	if ($status) then
	    echo ""$0": process $1 exited" >/dev/console
	    exit(1)
	endif
end

#
# time expired... 
# terminate the process
#
echo "time's up..." >/dev/console
echo ""$0": killing $1 ["$stpid"]..." >/dev/console

#
# kludge to get suntools to exit cleanly...
# search and destroy all cmdtool's 
#
set ctpid = ()
set ctpid = `ps -aux | grep cmdtool | grep -v grep | awk '{print $2}'`

if ($#ctpid != 0) then
	foreach i ($ctpid)
		kill -HUP $i >& /dev/null
	end
endif

#
# now kill the main process (suntools)
#
kill -HUP $stpid

exit(0)
