Timeout on shell command.

Jay A. Konigsberg jak at sactoh0.UUCP
Thu Aug 16 12:12:09 AEST 1990


In article <1990Aug12.221658.27776 at uncle.uucp> donlash at uncle.UUCP (Donald Lashomb) writes:
>In article <BRISTER.90Aug10222433 at westworld.decwrl.dec.com> brister at decwrl.dec.com (James Brister) writes:
>>I'd like to have a shell script run a command, but if that command doesn't
>>finish in X seconds, then the script should kill it, if the command
>>finishes sooner then the script should immediately continue. Any ideas on
=============================================================
>>how one could achieve this?
>
>I'd approach it like this-
>
>#!/bin/sh
>#
>#  run the command in the background
>#  remember its process ID
>#  sleep for X seconds
>#  kill the background command --- note: if
>#  the background command is finished, then
>#  the kill will fail benignly.
>#
>command &
>cmdpid=$!
>sleep $X
>kill $cmdpid
>
When I saw the original post, I almost answered with this type of solution.
However, it lacks an important part of the request. If the command finishes
early, execution will still wait for the sleep to complete.

However, there just may be a way if the sleep is placed in its own file.

# main program file
SEC={number here}        # set the number of seconds to wait
command &                # execute in background
cmdpid = $!              # save the PID
sleepit $SEC $cmdpid &   # sleep in background
wait $cmdpid             # wait for the process to complete or be killed

# sleepit - sleep $1 sec and then kill -9 $2
sleep $1
kill -9 $2 2>/dev/null #don't want those nasty error messages.

My thanks to Donald Lashomb's post. Without it, I wouldn't have come up
with this solution.

-- 
-------------------------------------------------------------
Jay @ SAC-UNIX, Sacramento, Ca.   UUCP=...pacbell!sactoh0!jak
If something is worth doing, its worth doing correctly.



More information about the Comp.unix.questions mailing list