linux下采用trap对信号进行捕捉

27 篇文章 0 订阅

 在Linux中,trap命令主要用于接收信号并采取行动,信号是异步发送到一个程序的事件,在默认情况下,可以终止一个程序,trap命令原型如下:

trap command signal

signal是指接收到的信号,command是接收到该信号采取的行动。如下为两种简单的信号。

信号

说明

INT(2)

Ctrl + C

QUIT(3)

Ctrl + \

示例代码如下

[root@localhost shell]# cat -n trap.sh 
     1	#!/bin/bash
     2	trap "echo 'sorry! I habe trapped Ctrl+C'" SIGINT SIGTERM
     3	echo this is a test program
     4	count=1
     5	while [ $count -le 10 ]
     6	do
     7		echo "LOOP #$count"
     8		sleep 5
     9		count=$[ $count + 1]
    10	done
    11	echo this is the end of the test program
[root@localhost shell]# 

运行时按下Ctrl+C结果如图:

[root@localhost shell]# ./trap.sh 
this is a test program
LOOP #1
LOOP #2
^Csorry! I habe trapped Ctrl+C
LOOP #3
LOOP #4
^Csorry! I habe trapped Ctrl+C
LOOP #5
LOOP #6
LOOP #7
LOOP #8
^Csorry! I habe trapped Ctrl+C
LOOP #9
LOOP #10
this is the end of the test program
[root@localhost shell]# 

如果想要捕捉shell脚本的退出,只要在trap命令上加EXIT信号就行,代码如下:

[root@localhost shell]# cat -n trap.sh 
     1	#!/bin/bash
     2	trap "echo 'sorry! I habe trapped Ctrl+C'" SIGINT SIGTERM
     3	trap "echo goodbye" EXIT
     4	echo this is a test program
     5	count=1
     6	while [ $count -le 10 ]
     7	do
     8		echo "LOOP #$count"
     9		sleep 5
    10		count=$[ $count + 1]
    11	done
    12	echo this is the end of the test program
[root@localhost shell]# 

运行结果如下:

[root@localhost shell]# ./trap.sh 
this is a test program
LOOP #1
^Csorry! I habe trapped Ctrl+C
LOOP #2
^Csorry! I habe trapped Ctrl+C
LOOP #3
^Csorry! I habe trapped Ctrl+C
LOOP #4
LOOP #5
LOOP #6
^Csorry! I habe trapped Ctrl+C
LOOP #7
^Csorry! I habe trapped Ctrl+C
LOOP #8
LOOP #9
LOOP #10
this is the end of the test program
goodbye
[root@localhost shell]# 

还可以在shell中移除捕捉,代码如下:

[root@localhost shell]# cat -n trap.sh 
     1	#!/bin/bash
     2	trap "echo 'sorry! I habe trapped Ctrl+C'" SIGINT SIGTERM
     3	trap "echo goodbye" EXIT
     4	echo this is a test program
     5	count=1
     6	while [ $count -le 10 ]
     7	do
     8		echo "LOOP #$count"
     9		sleep 1
    10		count=$[ $count + 1]
    11	done
    12	echo this is the end of the test program
    13	trap - EXIT
    14	echo "	I just remove EXIT trap "

在程序结束之前,移除了EXIT捕捉,最终就不会输出goodbye:

[root@localhost shell]# ./trap.sh 
this is a test program
LOOP #1
LOOP #2
LOOP #3
LOOP #4
LOOP #5
LOOP #6
LOOP #7
LOOP #8
LOOP #9
LOOP #10
this is the end of the test program
	I just remove EXIT trap 
[root@localhost shell]# 



  • 4
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值