我有“陷阱‘回响忽略’USR1”我叫脚本,为什么调用脚本被杀?(I have “trap '

2019-09-30 06:52发布

说我有这两个的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

捕兽应该陷阱USR1并直接将其忽略。 它开始usr1er,杀死其进程组与USR1信号。 现在,如果我开始捕兽从交互shell本身就是一个剧本,它杀死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

为什么?

Answer 1:

看来, $() 以单独的进程组/ PGID启动过程(apparantly制作Cc工作)。

此外,任何非交互的shell也不会启动单独的PGID的为他们的孩子(除非你开启与集-m作业控制):

$ bash -c '/tmp/trapper;echo done'
trapper: now killing usr1er
trapper: sleeping
usr1er: EXIT received, sending USR1
User defined signal 1
$ /tmp/trapper: line 9: 17522 Terminated              "$(dirname $0)"/usr1er
trapper: ignoring USR1
trapper: reached end of trapper

需要注意的是“做”不打印,外bash脚本,它不捕获USR1,是同时捕兽不断的生活,直到最后死亡。

您可以通过将检查每个进程的PGID ps -o %p%r%c -p$$的脚本:

$ /tmp/outer
  PID  PGID COMMAND
27630 27630 outer
  PID  PGID COMMAND
27633 27630 trapper
  PID  PGID COMMAND
27635 27630 usr1er
trapper: now killing usr1er
trapper: sleeping
usr1er: EXIT received, sending USR1
User defined signal 1
$ /tmp/trapper: line 9: 27635 Terminated              "$(dirname $0)"/usr1er
trapper: ignoring USR1
trapper: reached end of trapper


Answer 2:

试试这个变化

的/ tmp / usr1er:

#!/bin/bash
trap 'echo "usr1er: EXIT received, sending USR1"; kill -USR1 $PPID' TERM
while sleep 1;do echo usr1er: sleeping;done

处理TERM信号,而不是退出并发送USR1至$PPID ,而不是0



文章来源: I have “trap 'echo ignore' USR1” in my called script, why does the calling script get killed?