如何通过脚本的树状传播的信号?巴什 [英] How to propagate a signal through an arborescence of scripts ? Bash
问题描述
我有一个由一主一控制脚本的树状
I have an arborescence of scripts which are controlled by a main one
我想陷阱主脚本信号 CTRL-C
,并将其传播到其他
I want to trap the signal ctrl-c
in the main script and propagate it to the others
其他脚本应该捕获这个信号,以及(从主脚本),并做一些清理...
The other scripts should trap this signal as well ( from the main script ) and do some clean-up ...
我试图发送杀-s SIGINT
来的孩子,但他们似乎他们无法
捕捉信号(即使陷阱'清理'SIGINT
对孩子的脚本所定义)
I have tried to send kill -s SIGINT
to the children, but they seem they are unable to
catch the signal( even if trap 'Cleanup' SIGINT
being defined on the children scripts )
任何线索如何实现这一点?
Any clues how to realize this ?
问候,
调试
推荐答案
下面的示例演示,做父母的脚本的东西(睡眠5
)启动两个孩子后做自己的事情(也睡眠5
)。当父退出(无论何种原因),它标志着孩子终止(不要 SIGINT
,终止是由 SIGTERM $ C $信号C>,也是默认
杀
信号)。孩子们接着做 SIGTERM
接收他们的事。如果孩子是自己的脚本,我建议你改变的陷阱 - TERM
掉进陷阱的退出
使孩子们收拾不管他们终止的原因是什么(只要它捕获的)。
The following example demonstrates a parent script that does something (sleep 5
) after it starts two children that do their own thing (also sleep 5
). When the parent exits (for whatever reason) it signals the children to terminate (don't SIGINT
, termination is signaled by SIGTERM
, also the default kill
signal). The children then do their thing on reception of SIGTERM
. If the children are scripts of their own, I recommend you change the trap on TERM
into a trap on EXIT
so that the children clean up no matter what the cause of their termination be (so long as it's trappable).
请注意我用的等待
。击不中断运行的非内置命令,当它接收到信号。相反,它会等待他们完成且命令完成后处理的信号。如果你使用等
,bash将立即停止等待并处理信号的时候了。
Notice my use of wait
. Bash does not interrupt running non-builtin commands when it receives a signal. Instead, it waits for them to complete and handles the signal after the command is done. If you use wait
, bash stops waiting immediately and handles the signal right away.
#!/usr/bin/env bash
trap 'echo parent shutting down; kill $(jobs -p)' EXIT
{ trap 'echo child 1 signaled' TERM; sleep 5 & wait; } &
{ trap 'echo child 2 signaled' TERM; sleep 5 & wait; } &
sleep 5
这篇关于如何通过脚本的树状传播的信号?巴什的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!