“trap”在“exec”命令后不起作用

“trap”在“exec”命令后不起作用

我正在使用 bash 开发一个监控程序。该程序将连续运行,如果我更新 bash 代码,这应该重新运行新代码而不退出(基本上是热升级)。

我尝试通过使用 SIGUSR2 并再次执行相同的脚本来做到这一点。

它第一次工作正常,捕获 SIGUSR2 信号并执行新脚本。但是在第一次执行之后,它不再响应 SIGUSR2。

#!/bin/bash

VERSION=v1
upgrade()
{
    export GOT_UPGRADED=true
    echo "Upgrading..."
    exec $HOME/workspace/test/upgrade_test
}

init()
{
    if [[ $GOT_UPGRADED != true ]]; then
        # won't initialize again, if it's got upgraded.
        echo "Initializing..."
    fi
}

monitor()
{
    echo "$VERSION: Monitoring..."
}

trap upgrade SIGUSR2 # if SIGUSR2 is received, upgrade.

init
while true; do
    monitor
    sleep 1
done;

示例运行:

shell1: ./upgrade_test
Initializing...
v1: Monitoring...
v1: Monitoring...
v1: Monitoring...
v1: Monitoring...
v1: Monitoring...
Upgrading...                  # Sent from shell2
v1: Monitoring...
v1: Monitoring...
v1: Monitoring...
v1: Monitoring...

Meanwhile in shell2:
pkill -SIGUSR2 -f upgrade_test; # here it got upgraded
pkill -SIGUSR2 -f upgrade_test; # THE PROBLEM: doesn't work anymore

即使在执行后,如何保持 SIGUSR2 处理程序正常工作?

谢谢,

答案1

适用于bash4.4 版本

#!/bin/bash

########################################################################
#
trapped()
{
    echo "Oh oh I'm trapped"
    exec "$0" "$@"

    echo "exec failed: $0 $*"
    exit 1
}

########################################################################
# Go
#
trap trapped SIGUSR2

echo "Running new instance as PID $$"
while :
do
    read -p "$(date): " -t 120 X; ss=$?; echo
    [[ $ss -eq 1 ]] && exit
done

运行这个/tmp/trap.sh

Running new instance as PID 3899
11 Mar 2021 10:29:22: Oh oh I'm trapped
Running new instance as PID 3899
11 Mar 2021 10:29:36: Oh oh I'm trapped
Running new instance as PID 3899
11 Mar 2021 10:29:38:

相关内容