linux中的訊號簡介和trap命令
阿新 • • 發佈:2019-01-06
1.訊號
linux通過訊號來在執行在系統上的程序之間通訊,也可以通過訊號來控制shell指令碼的執行
主要有一下訊號
1 ##程序重新載入配置 2 ##刪除程序在記憶體中的資料 3 ##刪除滑鼠在記憶體中的資料 9 ##強行結束單個程序(不能被阻塞) 15 ##正常關閉程序 (可能被阻塞) 18 ##執行暫停的程序 19 ##暫停某個程序 (不能被阻塞) 20 ##把程序號打入後臺 man 7 signal ##檢視訊號詳細資訊
1)捕捉訊號:trap命令
#常用訊號 ctrl+c(終止程序) ctrl+z(暫停程序)
如上圖,訊號2與ctrl+c的作用時一樣的
stty -a ##列出中斷訊號與鍵盤的關係
trap "" 2 ##訊號遮蔽,此時按ctrl+c就不會有作用
trap : 2 ##恢復訊號
2)捕捉指令碼的退出
#!/bin/bash trap "echo 'Sorry!I have trapped Ctrl+C'" 2 echo "This is a test script~" count=1 while [ $count -le 10 ] do echo "Loop #$count" sleep 1 count=$[ $count + 1 ] done echo "This is the end of the script~" trap - 2 echo "I just removed the trap"
如上圖,當我執行這個指令碼的時候,ctrl+c是被trap住的,當指令碼執行結束後,ctrl+c就被釋放了
3)一個指令碼
執行這個指令碼會不停的新建以westos+時間組成的檔案,當使用ctrl+c命令時,會自動刪除所有新建的檔案
#!/bin/bash trap "find /tmp -type f -name "westos_*" | xargs rm -f && exit " 2 while true do touch /tmp/westos_$(date +%F-%N-%M-%S) sleep 2 ls -l /tmp/westos* done
來源:https://blog.csdn.net/weixin_40543283/article/details/85561804