加入收藏 | 设为首页 | 会员中心 | 我要投稿 云计算网_泰州站长网 (http://www.0523zz.com/)- 视觉智能、AI应用、CDN、行业物联网、智能数字人!
当前位置: 首页 > 服务器 > 搭建环境 > Linux > 正文

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

发布时间:2021-01-01 16:58:44 所属栏目:Linux 来源:网络整理
导读:我正在为应用程序编写一个bash包装器.该包装器负责更改用户,运行软件和记录其输出. 我也希望它传播SIGINT信号. 到目前为止,这是我的代码: #!/bin/bashset -e; set -ufunction child_of { ps --ppid $1 -o "pid" --no-headers | head -n1}function handle_

我正在为应用程序编写一个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

(编辑:云计算网_泰州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    热点阅读