Kill process after a given time bash?

LF4 picture LF4 · Oct 21, 2011 · Viewed 39.5k times · Source

I have a script that tries to make a DB connection using another program and the timeout(2.5min) of the program is to long. I want to add this functionality to the script.

If it takes longer then 5 seconds to connect, kill the process
Else kill the sleep/kill process.

The issue I'm having is how bash reports when a process is killed, that's because the processes are in the same shell just the background. Is there a better way to do this or how can I silence the shell for the kill commands?

DB_CONNECTION_PROGRAM > $CONNECTFILE &
pid=$! 
(sleep 5; kill $pid) &
sleep_pid=$!
wait $pid

# If the DB failed to connect after 5 seconds and was killed
status=$? #Kill returns 128+n (fatal error)
if [ $status -gt 128 ]; then
    no_connection="ERROR: Timeout while trying to connect to $dbserver"
else # If it connected kill the sleep and any errors collect
    kill $sleep_pid
    no_connection=`sed -n '/^ERROR:/,$p' $CONNECTFILE`
fi

Answer

Itay Perl picture Itay Perl · Oct 22, 2011

There's a GNU coreutils utility called timeout: http://www.gnu.org/s/coreutils/manual/html_node/timeout-invocation.html

If you have it on your platform, you could do:

timeout 5 CONNECT_TO_DB
if [ $? -eq 124 ]; then
    # Timeout occurred
else
    # No hang
fi