在Bash中识别接收到的信号名称 [英] Identifying received signal name in Bash
问题描述
当接收到信号时,我可以使用trap
执行一些命令.示例:
When a signal is received, I can execute some commands using trap
. Example:
trap 'echo hello world' 1 2
如果收到指定的任何信号,则显示"hello world".
If any of the signals specified is received, the hello world' is displayed.
但是我如何打印/识别接收到的信号名称?
But how can I print/identify the received signal name?
推荐答案
(如果您只有信号编号并需要名称,kill -l $SIGNAL_NUM
会打印信号名称;您可以通过使用信号来避免这种情况而不是在拨打trap
的电话中,如下所示.)
(If you only have the number of a signal and want the name, kill -l $SIGNAL_NUM
prints the name of a signal; you can avoid that by using the signal names instead of numbers in your call to trap
as below.)
此答案说,识别被困在bash中的哪个信号的唯一方法是为每个不同的信号编写一个单独的包装器你想陷井. 关于同一问题的另一个答案提供了包装函数来为您完成此操作:
This answer says that the only way to identify which signal you trapped in bash is to write a separate wrapper for each different signal you want to trap. Another answer on that same question provides a wrapper function to do it for you:
代码:
#!/bin/bash
trap_with_arg() {
func="$1" ; shift
for sig ; do
trap "$func $sig" "$sig"
done
}
func_trap() {
echo "Trapped: $1"
}
trap_with_arg func_trap INT TERM EXIT
echo "Send signals to PID $$ and type [enter] when done."
read # Wait so the script doesn't exit.
如果运行该命令,则可以向该进程发送信号,并得到类似的输出
If I run that, then I can send signals to the process and I get output like
Trapped: INT
Trapped: TERM
Trapped: EXIT
这篇关于在Bash中识别接收到的信号名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!