如何优雅地停止bash脚本中的无限循环? [英] How to stop infinite loop in bash script gracefully?
问题描述
我需要每隔X秒运行一次应用程序,因此,就cron不能以这种方式运行秒而言,我编写了一个bash脚本,其中包含X睡眠的无限循环.
I need to run application in every X seconds, so, as far as cron does not work with seconds this way, I wrote a bash script with infinite loop having X seconds sleep in it.
当我必须手动停止正在运行的脚本时,我想以一种正确的方式进行操作-让应用程序完成运行,而下次不再进入循环.
When I have to stop the running script manually, I would like to do it in a correct way - let the application complete functioning and just do not enter the loop for the next time.
您有什么想法,如何实现? 我曾考虑过传递参数,但找不到如何将参数传递给正在运行的脚本.
Do you have any idea, how this can be achieved? I thought about passing arguments, but I could not find how to pass argument to running script.
推荐答案
您可以捕获信号,例如SIGUSR1:
You could trap a signal, say SIGUSR1:
echo "My pid is: $$"
finish=0
trap 'finish=1' SIGUSR1
while (( finish != 1 ))
do
stuff
sleep 42
done
然后,当您想在下一次迭代中退出循环时:
Then, when you want to exit the loop at the next iteration:
kill -SIGUSR1 pid
其中pid
是脚本的进程ID.如果在睡眠期间发出信号,它将唤醒(睡眠进入睡眠状态,直到出现任何信号为止).
Where pid
is the process-id of the script. If the signal is raised during the sleep, it will wake (sleep sleeps until any signal occurs).
这篇关于如何优雅地停止bash脚本中的无限循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!