可能的重复:
运行命令指定时间,如果时间超过则中止
是否有一个命令允许我执行另一个命令最多 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 ...]
.