在子进程/后台进程中运行时,我无法捕获信号.
这是我简单的bash脚本:
#!/bin/bash echo "in child" trap "got_signal" SIGINT function got_signal { echo "trapped" exit 0 } while [ true ]; do sleep 2 done
当运行这个和以后做
kill -SIGINT (pid)
一切都符合预期,它打印“被困”并退出.
现在,如果我从父脚本启动相同的脚本,如下所示:
#!/bin/bash echo "starting the child" ./child.sh &
然后孩子不会陷入信号….?
更改后使用SIGTERM而不是SIGINT,它似乎正常工作?
OSX上的bash联机帮助页(但是在其他版本中应该是一样的)有关于信号处理的说法:
原文链接:https://www.f2er.com/bash/385897.htmlNon-builtin commands run by
bash
have signal handlers set to the values
inherited by the shell from its parent. When job control is not in
effect,asynchronous commands ignoreSIGINT
andSIGQUIT
in addition to
these inherited handlers.
进一步,在陷阱命令下:
Signals ignored upon entry to the shell cannot
be trapped or reset.
由于脚本默认情况下不使用作业控制,所以这就是您正在谈论的情况.