如何在同步执行期间处理bash中的信号?

时间:2012-10-12 10:00:33

标签: bash signals

我有一个bash脚本进程,它在某个时刻同步执行一个长时间运行的子进程。 在该子进程的运行期间,信号被直接发送到bash脚本进程,请求脚本终止。 有没有办法拦截那个信号,终止子进程然后退出bash进程?

显然,bash的信号处理从不中断同步调用?

我无法控制终止信号被发送到bash进程的事实。虽然如果信号可以传播到子进程,那也可以解决我的问题。

提前谢谢, Broes

3 个答案:

答案 0 :(得分:7)

请参阅bash的手册页, SIGNALS

一章

如果bash正在等待命令完成并收到已设置陷阱的信号,在命令完成之前不会执行陷阱。当bash通过wait builtin等待异步命令时,接收到已设置陷阱的信号将导致wait builtin立即返回,退出状态大于128,之后立即执行陷阱。 / p>

因此,异步运行外部程序并使用wait。用$ !.

杀死它

答案 1 :(得分:1)

这是我写的一个bash实用程序函数来处理这个问题。它被证明是有用和强大的。我希望你觉得它很有用。

# Run a command in a way that can be interrupted by a signal (eg SIGTERM)
#
# When bash receives a SIGTERM it normally simply exits. If it's executing a subprocess
# that subprocess isn't signaled. (Typically that's not a problem for interactive shells
# because the entire Process Group gets sent the signal.)
#
# When running a script it's sometimes useful for the script to propagate a SIGTERM
# to the command that was running. We can do that by using the trap builtin to catch
# the signal. But it's a little tricky, per the bash manual:
#
#    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.
#
# so a script executing a long-running command with a signal trap set won't
# notice the signal until later. There's a way around that though...
#
#    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.
#
# Usage:
#
#   interruptable [options] command [args]
#
# Options:
#   --killall - put the child into a process group (via setsid)
#               and send the SIGTERM to the process group
#   --debug   - print a message including pid of the child
#
# Usage examples:
#
#   interruptable sleep 3600
#
# If not interrupted, the exit status of the specified command is returned.
# If interrupted, the specified command is sent a SIGTERM and the current
# shell exits with a status of 143.

interruptable() {

    # handle options
    local setsid=""
    local debug=false
    while true; do
        case "${1:-}" in
            --killall)      setsid=setsid; shift ;;
            --debug)        debug=true; shift ;;
            --*)            echo "Invalid option: $1" 1>&2; exit 1;;
            *)              break;; # no more options
        esac
    done

    # start the specified command
    $setsid "$@" &
    local child_pid=$!

    # arrange to propagate a signal to the child process
    trap '
        exec 1>&2
        set +e
        trap "" SIGPIPE # ensure a possible sigpipe from the echo does not prevent the kill
        echo "${BASH_SOURCE[0]} caught SIGTERM while executing $* (pid $child_pid), sending SIGTERM to it"
        # (race) child may have exited in which case kill will report an error
        # if setsid is used then prefix the pid with a "-" to indicate that the signal
        # should be sent to the entire process group
        kill ${setsid:+-}$child_pid
        exit 143
    ' SIGTERM
    # ensure that the trap doesn't persist after we return
    trap 'trap - SIGTERM' RETURN

    $debug && echo "interruptable wait (child $child_pid, self $$) for: $*"

    # An error status from the child process will trigger an exception (via set -e)
    # here unless the caller is checking the return status
    wait $child_pid # last command, so status of waited for command is returned
}

答案 2 :(得分:0)

是的,可以使用trap命令拦截信号。请参阅以下示例:

#!/bin/bash
function wrap {
local flag=0
trap "flag=1" SIGINT SIGTERM
xeyes &
subppid=$!

while : 
    do
        if [ $flag -ne 0 ] ; then
            kill $subppid
            break 
        fi
            sleep 1        
    done
}
flag=0
trap "flag=1" SIGINT SIGTERM
wrap &
wrappid=$!
while :                 # This is the same as "while true".
    do
        if [ $flag -ne 0 ] ; then
            kill $wrappid
            break
        fi
        sleep 1        # This script is not really doing anything.
done
echo 'end'

trap基本上做的是它执行“”之间的命令。所以这里的主要功能是在下面的while循环中。在每次迭代中,脚本都会检查标志是否已设置,如果没有,则会暂停一秒钟。在此之前,我们通过$!记住了子进程的pid。捕获SIGINTSIGTERM时陷阱会发出命令(对于其他信号,请参阅kill手册)。

包装函数与main函数一样。此外,它调用实际的subprocess函数(在这种情况下,子进程为xeyes)。当包装函数从主函数接收到SIGTERM信号时(主函数也捕获了其中一个信号),包装函数可以在实际查杀子进程之前清理掉事物。之后它从while循环中断并退出包装函数。然后主函数也会打破并打印'end'

编辑: 希望我理解正确,你被迫执行xeyes &。然后步骤如下(终端):

xeyes &
subpid=$!
trap "kill $subpid && exit " SIGINT SIGTERM
.... other stuff
.... more stuff
^C #TERMINATE - this firstly kills xeyes and then exits the terminal