![x秒間コマンドを実行しますか? [コピー]](https://linux33.com/image/20623/x%E7%A7%92%E9%96%93%E3%82%B3%E3%83%9E%E3%83%B3%E3%83%89%E3%82%92%E5%AE%9F%E8%A1%8C%E3%81%97%E3%81%BE%E3%81%99%E3%81%8B%EF%BC%9F%20%5B%E3%82%B3%E3%83%94%E3%83%BC%5D.png)
最大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 ...]
。