如何通过一组脚本传播信号? [英] How to propagate a signal through a collection of scripts?

查看:104
本文介绍了如何通过一组脚本传播信号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组由主要脚本控制的脚本.我想在主脚本中捕获信号 ctrl + c 并将其传播给其他脚本.其他脚本也应该(从主脚本中)捕获该信号并进行一些清理...

我尝试将kill -s SIGINT发送给子级,但是他们似乎无法捕获信号(即使在子级脚本中定义了trap 'Cleanup' SIGINT)

任何线索如何实现这一目标?

解决方案

以下示例演示了一个父脚本,该脚本在启动两个自己做事的子级(也为sleep 5)后执行了某些操作(sleep 5).当父级退出时(出于某种原因),它会向子级发出终止信号(不要SIGINT,终止由SIGTERM信号,也是默认的kill信号).然后,孩子们在接受SIGTERM的时候做他们的事情.如果孩子是自己的脚本,我建议您将TERM上的陷阱更改为EXIT上的陷阱,以便无论终止原因是什么,孩子都可以清理(只要它是可捕获的). /p>

请注意我对wait的使用.当Bash收到信号时,它不会中断正在运行的非内置命令.相反,它将在命令完成后等待它们完成并处理信号.如果您使用wait,bash会立即停止等待并立即处理信号.

#!/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

I have an collection of scripts which are controlled by a main one. 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 ...

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?

解决方案

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).

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆