在bash shell脚本识别接收到的信号名称 [英] Identifying received signal name in bash shell script

查看:179
本文介绍了在bash shell脚本识别接收到的信号名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当接收到信号,我可以使用陷阱执行某些命令。如果指定的任何信号的接收,显示的hello world。例如:

When a signal is received, I can execute some commands using trap . If any of the signals specified is received, the hello world' is displayed. Example:

trap 'echo hello world' 1 2

但我怎么能打印/识别接收到的信号的名字吗?

But How can I print/identify the received signal name ?

推荐答案

(如果你只有一个信号的数量和所需的名称,杀-l $ SIGNAL_NUM 打印信号的名称,那么就可以避免使用信号名称,而不是在你的电话号码,以陷阱如下)

(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. It provides a wrapper function to do it for you:

code:

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

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 shell脚本识别接收到的信号名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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