子后台进程中的陷阱信号 [英] Trap signal in child background process
问题描述
在子进程/后台进程中运行时,我无法捕获信号.
I am unable to trap a signal when running in a child / background process.
这是我简单的bash脚本:
Here is my simple bash script :
#!/bin/bash
echo "in child"
trap "got_signal" SIGINT
function got_signal {
echo "trapped"
exit 0
}
while [ true ]; do
sleep 2
done
在运行此功能并稍后运行时
When running this and later do
kill -SIGINT (pid)
一切正常,打印出被困"并退出.
Everything works as expected, it prints 'trapped' and exits.
现在,如果我从这样的父脚本中启动相同的脚本:
Now, if I start the same script from a parent script like this :
#!/bin/bash
echo "starting the child"
./child.sh &
然后孩子不再捕获信号了....?
Then the child does not trap the signal anymore.... ?
更改为使用SIGTERM而不是SIGINT后,它似乎可以正常工作...?
After changing to use SIGTERM instead of SIGINT, it seems to be working correctly... ?
推荐答案
OSX上的bash
联机帮助页(但在其他版本中应该相同)中对信号处理的说法是这样的:
The bash
manpage on OSX (but it should be the same in other versions) has this to say about signal handling:
bash
运行的非内置命令将信号处理程序设置为以下值 由外壳程序从其父级继承.当作业控制不在时 效果是,异步命令除了会忽略SIGINT
和SIGQUIT
这些继承的处理程序.
Non-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.
,然后在trap
命令下:
进入外壳时忽略的信号不能 被困或重置.
Signals ignored upon entry to the shell cannot be trapped or reset.
由于默认情况下脚本不使用作业控制,所以这就是您要讨论的情况.
Since scripts don't use job control by default, this means the case you're talking about.
这篇关于子后台进程中的陷阱信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!