如何阻止信号杀死我的 Bash 脚本?

Pao*_*olo 6 bash signals kill

我想要一个无限循环继续运行,并且只被一个终止信号暂时中断。我试过 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
Run Code Online (Sandbox Code Playgroud)

我的代码在从另一个脚本获取 INT 信号后运行该函数一次,但以后再也不会运行了。它停止。

编辑:虽然我不小心把 en exit 放在函数的末尾,但在 Stack Overflow 上,我没有在我使用的实际代码中。无论哪种方式,它都没有区别。解决方案是 Tiago 描述的 SIGTERM。

Tia*_*opo 6

我相信你正在寻找SIGTERM

例子:

#! /bin/bash

trap -- '' SIGINT SIGTERM
while true; do
    date +%F_%T
    sleep 1
done
Run Code Online (Sandbox Code Playgroud)

运行这个例子cTRL+C不会杀死它,kill <pid>你也可以用kill -9 <pid>.

如果您不想CTRL+Z中断使用:trap -- '' SIGINT SIGTERM SIGTSTP