我想要一个无限循环继续运行,并且只是暂时被终止信号中断。我尝试过 SIGINT、SIGUSR1、SIGUSR2。所有这些似乎都停止了循环。我什至尝试过 SIGINFO,但 Linux 不支持。
#!/bin/bash
echo $$ > /tmp/pid # Save the pid
function do_something {
echo "I am doing stuff" #let's do this now, and go back to doing the thing that is to be done over and over again.
#exit
}
while :
do
echo "This should be done over and over again, but always wait for someething else to be done in between"
trap do_something SIGINT
while `true`
do
sleep 1 #so we're waiting for that other thing.
done
done
我的代码在从另一个脚本获取 INT 信号后运行该函数一次,但之后就不再运行了。它停止了。
编辑:虽然我不小心将 en exit 放在函数末尾,但在 Stack Overflow 上,我在实际使用的代码中并没有这样做。不管怎样,都没有什么区别。解决方案是 Tiago 所描述的 SIGTERM。
最佳答案
我相信您正在寻找SIGTERM
:
示例:
#! /bin/bash
trap -- '' SIGINT SIGTERM
while true; do
date +%F_%T
sleep 1
done
运行此示例 cTRL+C
不会杀死它,也不会 kill <pid>
不过你可以用 kill -9 <pid>
杀死它.
如果你不想CTRL+Z
中断使用:trap -- '' SIGINT SIGTERM SIGTSTP
关于bash - 如何阻止信号杀死我的 Bash 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24848843/