0

Possible Duplicate:
Run a command for a specified time and then abort if time exceeds

Is there a command which allows me to execute another command for at most x seconds?

Imagined example: runonlyxseconds -s 5 <the real command and its args>

After that it would be forcefully terminated (e.g. first sending SIGTERM and if it doesn't work, SIGKILL).

thx

5

1 Answer 1

1

A pure bash solution using only near-universally available system commands:

timeout() {
    if (( $# < 3 )); then
        printf '%s\n' 'Usage: timeout sigterm-seconds sigkill-seconds command [arg ...]'
        return 1
    fi

    "${@:3}" &
    pid=$!

    sleep "$1"

    if ps "${pid}" >/dev/null 2>&1; then
        kill -TERM "${pid}"
        sleep "$2"
        if ! ps "${pid}" >/dev/null 2>&1; then
            printf '%s\n' "Process timed out, and was terminated by SIGTERM."
            return 2
        else
            kill -KILL "${pid}"
            sleep 1
            if ! ps "${pid}" >/dev/null 2>&1; then
                printf '%s\n' "Process timed out, and was terminated by SIGKILL."
                return 3
            else
                printf '%s\n' "Process timed out, but can't be terminated (SIGKILL ineffective)."
                return 4
            fi
        fi
    else
        printf '%s\n' "Process exited gracefully before timeout."
    fi
}

Then run as timeout sigterm-seconds sigkill-seconds command [arg ...].

Not the answer you're looking for? Browse other questions tagged .