I don't quite understand
-$$
. It evaluates to '-<PID>` eg
-1234
. In the kill manpage // builtin manpage a leading dash specifies the signal to be sent. However -- probably blocks that, but then the leading dash is undocumented otherwise. Any help?
@EvanBenn:查看
man 2 kill
,它解释了当一个PID为负数时,信号会被发送到进程组中的所有进程,并提供ID(
en.wikipedia.org/wiki/Process_group
). 令人困惑的是,在
man 1 kill
或
man bash
中没有提到这一点,可以认为是文档中的一个错误。
#!/bin/bash
# killable-shell.sh: Kills itself and all children (the whole process group) when killed.
# Adapted from http://stackoverflow.com/a/2173421 and http://veithen.github.io/2014/11/16/sigterm-propagation.html
# Note: Does not work (and cannot work) when the shell itself is killed with SIGKILL, for then the trap is not triggered.
trap "trap - SIGTERM && echo 'Caught SIGTERM, sending SIGTERM to process group' && kill -- -$$" SIGINT SIGTERM EXIT
echo $@
PID=$!
wait $PID
trap - SIGINT SIGTERM EXIT
wait $PID
cleanup() {
# kill all processes whose parent is this process
kill $(pidtree $$ | tac)
pidtree() (
[ -n "$ZSH_VERSION" ] && setopt shwordsplit
declare -A CHILDS
while read P PP;do
CHILDS[$PP]+=" $P"
done < <(ps -e -o pid= -o ppid=)
walk() {
echo $1
for i in ${CHILDS[$1]};do
walk $i
for i in "$@";do
walk $i
trap cleanup EXIT