Uma solução bash
pura usando apenas comandos do sistema quase universalmente disponíveis:
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
}
Em seguida, execute como timeout sigterm-seconds sigkill-seconds command [arg ...]
.