Killing the correct process

Geoff Clare gwc at root.co.uk
Fri Feb 9 21:50:31 AEST 1990


In article <5312 at star.cs.vu.nl> maart at cs.vu.nl (Maarten Litmaath) writes:
>In article <22332 at adm.BRL.MIL>,
>	marwood at ncs.dnd.ca (Gordon Marwood) wants to timeout ftp.
>
>How about using the following general purpose script?  If that's out of the
>question, the script might still give you a hint how to solve your problem.

[ extremely complicated script deleted ]

There is a much simpler way than Maarten's.

The basic strategy is:

	(sleep $time; kill $$) & exec "$@"

Here is my "timeout" command, using this method with added frills.
An important feature which Maarten's script lacks, is that mine kills
the process with SIGTERM, allowing it to clean up.  It only goes for
SIGKILL if the SIGTERM doesn't do the job.  Maarten dives straight
for SIGKILL, which could leave a mess.

---------------------- cut here ----------------------
:
# execute a command with timeout
# Geoff Clare <gwc at root.co.uk>, Feb 1990

USAGE="usage: $0 [-v] [seconds] command args ..."

SIGKILL=9	# may be system dependant

time=10		# default 10 seconds
verbose=n
for i in 1 2
do
	case $1 in
	-v)
		verbose=y
		shift
		;;
	[0-9]*)
		time=$1
		shift
		;;
	""|-*)
		echo >&2 "$USAGE"
		exit 1
		;;
	esac
done

pid=$$
(
	sleep "$time"
	# use SIGTERM first to allow process to clean up
	kill $pid >/dev/null 2>&1
	rc=$?
	sleep 2

	# if process hasn't died yet, use SIGKILL
	kill -$SIGKILL $pid >/dev/null 2>&1

	case "$rc$verbose" in
	0y) echo >&2 "
TIMED OUT \"$*\""
		;;
	esac
) &

exec "$@"
---------------------- cut here ----------------------

-- 
Geoff Clare, UniSoft Limited, Saunderson House, Hayne Street, London EC1A 9HH
gwc at root.co.uk  (Dumb mailers: ...!uunet!root.co.uk!gwc)  Tel: +44-1-315-6600
                                         (from 6th May 1990): +44-71-315-6600



More information about the Comp.unix.questions mailing list