Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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

share|improve this question

marked as duplicate by Gilles, Michael Mrozek Feb 2 '12 at 2:53

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Wall clock time or CPU time? If it's CPU time, see Can I limit a process to a certain amount of time / CPU cycles? –  Gilles Feb 2 '12 at 0:50
    
BashFAQ/068 –  jw013 Feb 2 '12 at 1:08
    
Oh, and if it's wall clock time, see Run a command for a specified time and then abort if time exceeds –  Gilles Feb 2 '12 at 1:22
1  
er, why not just use the "timeout" command ? –  Sirex Feb 2 '12 at 15:38
    
@Sirex: O_O. Seems I tried this on a Debian installation having no coretuils package. Thx! –  mark Feb 3 '12 at 17:20
add comment

1 Answer 1

up vote 1 down vote accepted

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 ...].

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.