linux shell:使用trap来处理信号
shell脚本可以使用trap来处理信号
命令语法如下:
trap 'signal_handler_function_name' SIGNAL LIST
SIGNAL LIST以空格分隔,它可以是信号编号或者信号名称。
下面的例子中,三个函数分别处理信号SIGINT、SIGTSTP和SIGTERM,
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$
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
doneqingsong@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$

本文介绍如何在Linux shell脚本中使用trap命令处理不同类型的信号。通过具体示例展示了如何定义信号处理函数来响应SIGINT、SIGTSTP和SIGTERM等信号,并解释了这些信号在实际场景中的应用。

4万+

被折叠的 条评论
为什么被折叠?



