Timeout
執行命令 x 秒?
可能重複:
是否有一個命令允許我最多執行另一個命令 x 秒?
想像的例子:
runonlyxseconds -s 5 <the real command and its args>
之後它將被強制終止(例如,第一次發送
SIGTERM
,如果它不起作用,SIGKILL
)。謝謝
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 ...]
.