linux – 防止bash脚本在处理SIGINT后终止

我正在为应用程序编写一个bash包装器.该包装器负责更改用户,运行软件和记录其输出.
我也希望它传播SIGINT信号.

到目前为止,这是我的代码

#!/bin/bash
set -e; set -u

function child_of {
    ps --ppid $1 -o "pid" --no-headers | head -n1
}

function handle_int {
    echo "Received SIGINT"
    kill -int $(child_of $SU_PID)
}

su myuser -p -c "bash /opt/loop.sh 2>&1 | tee -i >(logger -t mytag)" &
SU_PID=$!

trap "handle_int" SIGINT

wait $SU_PID
echo "This is the end."

我的问题是,当我向这个包装器发送一个SIGINT时,handle_int被调用但是脚本结束了,而我希望它继续等待$SU_PID.

有没有办法捕获int信号,做一些事情,然后阻止脚本终止?

最佳答案
你有一个问题:在Ctrl-C之后,“这就是结束.”预计但它永远不会到来,因为脚本已经过早退出.原因是在set -e下运行时wait(意外地)返回非零值.

根据“男子打击”:

If bash is waiting for a command to complete and receives a signal for which a trap has been set,the trap
will not be executed until the command completes. When bash is waiting for an asynchronous command via the
wait builtin,the reception of a signal for which a trap has been set will cause the wait builtin to return
immediately with an exit status greater than 128,immediately after which the trap is executed.

您应该将set wait包装在set e中,以便在等待异步命令时处理捕获的信号后程序可以继续运行.

像这样:

# wait function that handles trapped signal on asynchronous commands.
function safe_async_wait {
  set +e
  wait $1 # returns >128 on asynchronous commands
  set -e
}
#...
safe_async_wait $SU_PID

相关文章

在Linux上编写运行C语言程序,经常会遇到程序崩溃、卡死等异...
git使用小结很多人可能和我一样,起初对git是一无所知的。我...
1. 操作系统环境、安装包准备 宿主机:Max OSX 10.10.5 虚拟...
因为业务系统需求,需要对web服务作nginx代理,在不断的尝试...
Linux模块机制浅析 Linux允许用户通过插入模块,实现干预内核...
一、Hadoop HA的Web页面访问 Hadoop开启HA后,会同时存在两个...