linux下採用trap對訊號進行捕捉

2021-06-19 09:10:43 字數 2688 閱讀 9817

在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

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

loop #3

loop #4

loop #5

loop #6

loop #7

loop #8

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

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

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

goodbye

[root@localhost shell]#

還可以在shell中移除捕捉,**如下:

[root@localhost shell]# cat -n trap.sh 

1 #!/bin/bash

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]#

linux下trap命令和SIGHUP訊號量詳解

trap命令用於指定在接收到訊號後將要採取的動作。常見的用途是在指令碼程式被中斷時完成清理工作。我在寫自動公升級指令碼的時候,為防止指令碼執行期間是不能允許其使用ctrl c等中斷退出的,故使用了trap命令。一 關於訊號 歷史上,shell總是用數字來代表訊號,而新de指令碼程式應該使用訊號de名...

Linux下的訊號

訊號是作業系統發給程序的一種資訊,程序會針對接收到的資訊做出相應的處理。前面談到乙個概念,叫做訊號量,這裡所說的訊號量和我們今天談到的訊號,除了名字相似,事實上並沒有任何聯絡,是兩個完全不相關的概念,故不可混為一談。訊號是如何產生的呢?先來說說熟悉的場景 使用者輸入命令,在前台啟動乙個程序,然後按下...

Linux下shell中採用openssl加密

參考 這篇文章寫得非常好,給滿分 下面附上自己對照著擼出來的 僅僅當作筆記記錄 bin bash password gmengine 123 echo password openssl enc aes 256 cbc s 1ae3b897 out pass.aes pass pass 1231kj1...