我有一个 bash 脚本进程,它有时会同步执行一个长时间运行的子进程。在该子进程运行期间,会直接向 bash 脚本进程发送一个信号,请求脚本终止。有没有办法拦截该信号,终止子进程然后退出 bash 进程?
显然,bash 的信号处理永远不会中断同步调用?
我无法控制将终止信号发送到 bash 进程的事实。虽然如果信号可以传播到子进程,那也可以解决我的问题。
在此先感谢,兄弟
请参阅 bash 的手册页,SIGNALS一章:
如果 bash 正在等待命令完成并接收到已设置陷阱的信号,则在命令完成之前不会执行陷阱。当 bash 通过 wait builtin 等待异步命令时,接收到设置了陷阱的信号将导致 wait builtin 立即返回,退出状态大于 128,然后立即执行陷阱。
因此,异步运行您的外部程序并使用等待。使用 $! 杀死它。
这是我编写的用于处理此问题的 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
}
是的,可以用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 $!
。当SIGINT
或SIGTERM
被捕获时,陷阱会发出命令(有关其他信号,请参阅kill
手册)。
包装函数的作用与主函数相同。此外,它调用实际subprocess
函数(在这种情况下 subprocess 是xeyes
)。当包装函数接收到来自主函数SIGTERM
的信号(主函数也捕捉到其中一个信号)时,包装函数可以在实际杀死子进程之前清理东西。之后,它从 while 循环中中断并退出包装函数。然后 main 函数也中断并打印'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