通过引用bash:静默地杀死后台函数进程并在bash 中使命令超时而没有不必要的延迟,我编写了自己的脚本来为命令设置超时以及使kill消息静音。
但是当我的进程被终止时,我仍然收到“已终止”消息。我的代码有什么问题?
#!/bin/bash
silent_kill() {
kill $1 2>/dev/null
wait $1 2>/dev/null
}
timeout() {
limit=$1 #timeout limit
shift
command=$* #command to run
interval=1 #default interval between checks if the process is still alive
delay=1 #default delay between SIGTERM and SIGKILL
(
((t = limit))
while ((t > 0)); do
sleep $interval;
#kill -0 $$ || exit 0
((t -= interval))
done
silent_kill $$
#kill -s SIGTERM $$ && kill -0 $$ || exit 0
sleep $delay
#kill -s SIGKILL $$
) &> /dev/null &
exec $*
}
timeout 1 sleep 10
Run Code Online (Sandbox Code Playgroud)
您的代码没有任何问题,“终止”消息不是来自您的脚本,而是来自调用 shell(您从中启动脚本的 shell)。
您可以通过禁用作业控制来停用:
$ set +m
$ bash <your timeout script>
Run Code Online (Sandbox Code Playgroud)