[英]How to immediately skip loop and go to trap on kill command to process? [BASH]
My script: 我的剧本:
#!/bin/bash
finish() {
echo "[$(date -u)] I was terminated."
exit
}
trap finish SIGINT SIGTERM
echo "pid is $$"
while true
do
echo 'I am running'
sleep 15
done
When I send command kill -SIGTERM <pid>
to the process running my script I have to wait till sleep 15
would be executed. 当我向运行我的脚本的进程发送命令
kill -SIGTERM <pid>
,我必须等到sleep 15
被执行。 I googled but didn't find any answers how to immediately break out of the loop and go to executing trap
when I send kill
command. 我用谷歌搜索,但没有找到任何答案,当我发送
kill
命令时,如何立即跳出循环并执行trap
。
This question has been more or less answered here: Linux: How to kill Sleep . 这个问题或多或少在这里得到了回答: Linux:如何杀死Sleep 。 In short, the
bash
shell executing the script gets the kill signal, but the sleep
call does not. 简而言之,执行脚本的
bash
shell会获得kill信号,而sleep
调用不会。
If you want a process to sleep you can execute the sleep
in the background while you do a wait
on it. 如果您希望某个进程进入睡眠状态,则可以在
wait
在后台执行sleep
。 That way, the parent process will get your signal and be free to deal with it. 这样,父进程将收到您的信号并可以自由处理。 In your code:
在您的代码中:
#!/bin/bash
finish() {
echo "[$(date -u)] I was terminated."
exit
}
trap finish SIGINT SIGTERM
echo "pid is $$"
while true
do
echo 'I am running'
sleep 15 &
wait
done
Bear in mind that your kill signal will be caught by the parent process which will terminate immediately, but the sleep 15
will still run in the background until it finishes. 请记住,您的kill信号将被父进程捕获,该进程将立即终止,但是
sleep 15
仍将在后台运行直到完成。 You may kill this sleeping process by adding kill $!
您可以通过添加
kill $!
来终止此睡眠过程kill $!
which kills the last background process executed by bash
. 这杀死了
bash
执行的最后一个后台进程。
One final remark. 最后一句话。
wait
may wait for one or more processes to finish. wait
可能会等待一个或多个过程完成。 With no arguments it will wait for all the child processes to finish. 没有任何参数,它将等待所有子进程完成。 It will also return the status of the last process that finished if a process was specified.
如果指定了进程,它还将返回最后完成的进程的状态。 If not (like in the example), it will return 0.
如果不是(如示例中所示),它将返回0。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.