최대 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 ...]
.