假设我有这两个 bash 脚本:
/tmp/陷阱:
#!/bin/bash
trap 'echo trapper: ignoring USR1' USR1
"$(dirname $0)"/usr1er & p=$!
sleep 1
echo trapper: now killing usr1er
kill $p
echo trapper: sleeping
sleep 1
echo trapper: reached end of trapper
/tmp/usr1er:
#!/bin/bash
trap 'echo "usr1er: EXIT received, sending USR1"; kill -USR1 0' EXIT
while sleep 1;do echo usr1er: sleeping;done
Trapper 应该捕获 USR1 并简单地忽略它。它启动 usr1er,它使用 USR1 信号终止其进程组。现在,如果我从交互式 shell 中将 trapper 作为脚本单独启动,它会杀死 usr1er 并正常退出:
$ /tmp/trapper; echo done
trapper: now killing usr1er
trapper: sleeping
usr1er: EXIT received, sending USR1
/tmp/trapper: line 9: 16596 Terminated "$(dirname $0)"/usr1er
trapper: ignoring USR1
trapper: reached end of trapper
done
如果我尝试$(/tmp/trapper)
,它会退出整个外壳。同样,如果我制作一个单独的脚本来调用/tmp/trapper
,例如/tmp/outer
:
#!/bin/bash
"$(dirname $0)"/trapper
echo outer: reached end of outer
它被杀死而不打印“到达外部的末端”:
$ /tmp/outer
trapper: now killing usr1er
trapper: sleeping
usr1er: EXIT received, sending USR1
User defined signal 1
/tmp/trapper: line 9: 23544 Terminated "$(dirname $0)"/usr1er
User defined signal 1
trapper: ignoring USR1
trapper: reached end of trapper
为什么?