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

前端之家收集整理的这篇文章主要介绍了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
原文链接:https://www.f2er.com/linux/439968.html

猜你在找的Linux相关文章