问题描述
在子进程/后台进程中运行时,我无法捕获信号.
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:
,然后在trap
命令下:
由于默认情况下脚本不使用作业控制,所以这就是您要讨论的情况.
Since scripts don't use job control by default, this means the case you're talking about.
这篇关于子后台进程中的陷阱信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!