linux shell:使用trap来处理信号

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qingsong3333/article/details/77624394
linux shell:使用trap来处理信号

shell脚本可以使用trap来处理信号

命令语法如下:
    trap 'signal_handler_function_name' SIGNAL LIST
SIGNAL LIST以空格分隔,它可以是信号编号或者信号名称。

下面的例子中,三个函数分别处理信号SIGINT、SIGTSTP和SIGTERM,

qingsong@db2a:/tmp$ cat signal.sh

#!/bin/bash
#filename: signal.sh

function handle_INT()
{
        echo I received signal : SIGINT, will do nothing
}

function handle_STP()
{
        echo I received signal : SIGTSTP, will do nothing
}

function handle_TERM()
{
        echo I received signal : SIGTERM. I will exit now
        exit
}

echo "My PID is $$"

trap 'handle_INT' SIGINT
trap 'handle_STP' SIGTSTP
trap 'handle_TERM' SIGTERM

while :
do
        sleep 1
done

qingsong@db2a:/tmp$ bash signal.sh 
My PID is 51100
^CI received signal : SIGINT, will do nothing <--当前session里按下了Ctrl+c
I received signal : SIGINT, will do nothing   <--另一个session里发出命令kill -SIGINT 51100
I received signal : SIGTSTP, will do nothing  <--另一个session里发出命令kill -SIGTSTP 51100
I received signal : SIGTERM. I will exit now  <--另一个session里发出命令kill -SIGTERM 51100
qingsong@db2a:/tmp$

没有更多推荐了,返回首页