【发布时间】:2015-09-13 16:10:26
【问题描述】:
通过引用 bash: silently kill background function process 和 Timeout a command in bash without unnecessary delay,我编写了自己的脚本来设置命令的超时时间,以及使终止消息静音。
但是当我的进程被终止时,我仍然收到“终止”消息。我的代码有什么问题?
#!/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
【问题讨论】:
-
有什么问题?
-
@SMA 我不想从终端得到“终止”。
-
我觉得这可能是退后一步并想知道您将其用于什么目的的好时机。 “已终止”消息是有关您启动的命令的有用信息:它恰好是由于信号而不是正常进程完成而结束。您的 cmets 使您看起来对此不感兴趣。如果您不想让命令调用对父 shell 尽可能透明,那么使用
exec包装器毫无意义;您最好将该命令作为后台任务启动并从前台脚本中监视它。 -
(除非你需要终端 I/O,但在交互过程中需要超时中断似乎很奇怪。)