![x초 동안 명령을 실행하시겠습니까? [복사]](https://linux55.com/image/20623/x%EC%B4%88%20%EB%8F%99%EC%95%88%20%EB%AA%85%EB%A0%B9%EC%9D%84%20%EC%8B%A4%ED%96%89%ED%95%98%EC%8B%9C%EA%B2%A0%EC%8A%B5%EB%8B%88%EA%B9%8C%3F%20%5B%EB%B3%B5%EC%82%AC%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 ...]
.