Categories
FreeBSD/Unix

Timeout for a command called from a shell script

If a called program stop’s responding it causes the whole shell script to stop and wait for indefinite amount of time for the called program to finish. One way to avoid this is described below where simple timeout is created with help of sleep command and if the command is not able to finish during that time a kill is called to stop the execution of the command.

    #/bin/sh
    # Author: Jan Melen-jan(at)melen.org
    #
    TIMEOUT=600
    SIGNAL="INT"

    <fill your command and params here> &
    PID=$!
    if [ "${PID}" != "0" ]; then
        (sleep "${TIMEOUT}";  kill "${SIGNAL}" "${PID}") &
        KILLER=$!
        wait "${PID}" 2>/dev/null
        R=$?
        kill -HUP "${KILLER}" 2>/dev/null
        if [ $R -ne 0 ]; then
            echo "*** ERROR: Command exited with an error ***"
        fi
    fi