多个庆典陷阱相同的信号 [英] multiple bash traps for the same signal
问题描述
当我在bash使用陷阱命令,对于给定信号previous陷阱将被替换。
When I use the "trap" command in bash, the previous trap for the given signal is replaced.
有使多个陷阱火为同一信号的一种方式?
Is there a way of making more than one trap fire for the same signal?
推荐答案
编辑:
看来我误解的问题。答案很简单:
It appears that I misread the question. The answer is simple:
handler1 () { do_something; }
handler2 () { do_something_else; }
handler3 () { handler1; handler2; }
trap handler3 SIGNAL1 SIGNAL2 ...
原文:
只要在命令的末尾列出多个信号
Just list multiple signals at the end of the command:
trap function-name SIGNAL1 SIGNAL2 SIGNAL3 ...
您可以找到使用陷阱-p特定的信号
相关联的功能:
You can find the function associated with a particular signal using trap -p
:
trap -p SIGINT
请注意,它单独列出,即使它们是由相同的函数处理的每个信号。
Note that it lists each signal separately even if they're handled by the same function.
您可以给出一个已知的通过这样增加一个额外的信号:
You can add an additional signal given a known one by doing this:
eval "$(trap -p SIGUSR1) SIGUSR2"
此工作,即使存在由相同功能正在处理其它附加信号。换句话说,假设一个函数已经处理三个信号 - 你可以添加两个只是参照一个现有的和追加两个(其中只有一个是上面显示刚刚闭幕引号)
This works even if there are other additional signals being processed by the same function. In other words, let's say a function was already handling three signals - you could add two more just by referring to one existing one and appending two more (where only one is shown above just inside the closing quotes).
如果你正在使用bash> = 3.2,你可以做这样的事情,提取给出的信号的功能。请注意,这不是一个完全健壮,因为其他的单引号可能出现。
If you're using Bash >= 3.2, you can do something like this to extract the function given a signal. Note that it's not completely robust because other single quotes could appear.
[[ $(trap -p SIGUSR1) =~ trap\ --\ \'([^\047])\'.* ]]
function_name=${BASH_REMATCH[1]}
然后,你可以从头开始,如果你需要使用的函数名,等重建你的陷阱命令。
Then you could rebuild your trap command from scratch if you needed to using the function name, etc.
这篇关于多个庆典陷阱相同的信号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!