x秒間コマンドを実行しますか? [コピー]

x秒間コマンドを実行しますか? [コピー]

重複の可能性:
指定した時間だけコマンドを実行し、タイムアウトした場合は中断します。

最大x秒間別のコマンドを実行できるコマンドはありますか?

想像の例:runonlyxseconds -s 5 <the real command and its args>

SIGTERMその後は強制的に終了します(たとえば、機能しない場合は最初に送信されたとき)SIGKILL

ありがとう

ベストアンサー1

bashほぼ一般的なシステムコマンドのみを使用する純粋なソリューション:

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
}

それからtimeout sigterm-seconds sigkill-seconds command [arg ...]

おすすめ記事