文章作者:Tyan
博客:noahsnail.com ?|? CSDN ?|? 簡書
1. Linux信號
Linux系統(tǒng)利用信號與系統(tǒng)中的進程進行通信牌借。Linux的常見信號有:
信號 | 值 | 描述 |
---|---|---|
1 | SIGHP | 掛起進程 |
2 | SIGINT | 終止進程 |
3 | SIGQUIT | 停止進程 |
9 | SIGKILL | 無條件終止進程 |
15 | SIGTERM | 盡可能終止進程 |
17 | SIGSTOP | 無條件停止進程,但不是終止進程 |
18 | SIGTSTP | 停止或暫停進程牙甫,但不終止進程 |
19 | SIGCONT | 繼續(xù)運行停止的進程 |
2. 信號組合鍵
Ctrl+C組合鍵會產(chǎn)生SIGINT信號,Ctrl+Z會產(chǎn)生SIGTSTP信號军援。
3. trap命令
trap命令允許你來指定shell腳本要監(jiān)視并攔截的Linux信號桩警。trap命令的格式為:trap commands signals
捞慌。
demo1
shell腳本:
#!/bin/bash
# test trap command
trap "echo 'Sorry! I have trapped Ctrl-C'" SIGINT
echo This is a test script
count=1
while [ $count -le 10 ]
do
echo "Loop $count"
sleep 1
count=$[ $count + 1 ]
done
echo The end.
運行結(jié)果:
This is a test script
Loop 1
Loop 2
^CSorry! I have trapped Ctrl-C
Loop 3
Loop 4
^CSorry! I have trapped Ctrl-C
Loop 5
Loop 6
Loop 7
Loop 8
^CSorry! I have trapped Ctrl-C
Loop 9
Loop 10
The end.
demo2
除了在shell腳本中捕獲信號外淤堵,也可以在shell退出時捕獲寝衫,在trap命令后加上EXIT信號就行。
shell腳本:
#!/bin/bash
# test trap command
trap "echo Goodbye." EXIT
echo This is a test script
count=1
while [ $count -le 10 ]
do
echo "Loop $count"
sleep 1
count=$[ $count + 1 ]
done
echo The end.
運行結(jié)果:
This is a test script
Loop 1
Loop 2
Loop 3
Loop 4
Loop 5
Loop 6
Loop 7
Loop 8
Loop 9
Loop 10
The end.
Goodbye.
demo3——修改trap操作
#!/bin/bash
# test trap command
trap "echo 'Sorry! I have trapped Ctrl-C'" SIGINT
count=1
while [ $count -le 5 ]
do
echo "Loop $count"
sleep 1
count=$[ $count + 1 ]
done
trap "echo 'Sorry! The trap has been modified.'" SIGINT
count=1
while [ $count -le 5 ]
do
echo "Loop $count"
sleep 1
count=$[ $count + 1 ]
done
echo The end.
運行結(jié)果:
Loop 1
Loop 2
Loop 3
^CSorry! I have trapped Ctrl-C
Loop 4
Loop 5
Loop 1
Loop 2
Loop 3
^CSorry! The trap has been modified.
Loop 4
Loop 5
The end.
demo4
刪除捕獲拐邪,命令形式為:trap -- ***
慰毅,例如trap -- SIGINT
參考資料
- Linux命令行與shell腳本大全