標籤:terminal 分享 舉例 stop time 建立 amp blog log
shell中,向進程發送訊號多多通過ctrl鍵加上一些功能鍵來實現,這裡是常見的Ctrl按鍵組合及其意義:
按鍵組合 |
訊號類型 |
意義 |
Ctrl+C |
INT訊號,即interrupt訊號 |
停止運行當前的作業 |
Ctrl+Z |
TSTP訊號,即terminal stop訊號 |
使當前作業暫時停止(轉入阻塞狀態) |
Ctrl+\ |
QUIT訊號 |
Ctrl+C訊號的強化版本,當Ctrl+C無法停止作業試,使用該按鍵組合 |
Ctrl+Y |
TSTP訊號,即terminal stop訊號 |
當進程從終端讀取輸入資料是,暫時停止該進程 |
子she‘ll能繼承父she‘ll所忽略的訊號,但是不能繼承父she‘llwei未忽略的訊號,我們舉例來論證這一觀點,建立兩個指令碼forever.sh和subsig.sh,forever.sh內容如下:
#forever.sh示範無限迴圈等待#!/bin/bashwhile :; do #冒號相當於true. sleep 5done
forever.sh指令碼是提供subsig.sh指令碼調用建立子shell的,功能就是無限迴圈,每次迴圈睡5秒,即forever.sh指令碼永遠不會停止,除非被kill命令殺掉。subsig.sh內容如下:
#!/bin/bashtrap "" QUIT #忽略QUIT訊號trap "echo ‘You want to kill me‘" TERM #捕捉到TERM訊號後列印提示資訊(./forever.sh #將forever.sh指令碼作為子shell,子shell將無限休眠)
View Code
subsig.sh使用了兩次trap命令,將QUIT訊號忽略,但是不忽略TERM訊號,捕捉到TERM訊號後,需要列印提示資訊,然後利用圓括弧建立子shell,下面是父子shell處理QUIT和TERM訊號的測試過程:
[[email protected] shellScript]$ ./subsig.sh & #運行subsig.sh指令碼[1] 5118 #返回父shell作業號和進程號[[email protected] shellScript]$ kill -3 5118 #向父she‘ll發送3號訊號,即QUIT訊號[[email protected] shellScript]$ ps -a #父shell未退出,說明QUIT訊號被忽略 PID TTY TIME CMD 3822 pts/0 00:00:00 su 3830 pts/0 00:00:00 bash 3868 pts/0 00:00:00 su 3869 pts/0 00:00:00 bash 4037 pts/0 00:00:00 vim 4038 pts/0 00:00:00 vim 4418 pts/0 00:00:00 traploop.sh 4499 pts/0 00:00:00 sleep 5118 pts/0 00:00:00 subsig.sh 5119 pts/0 00:00:00 forever.sh 5123 pts/0 00:00:00 sleep 5124 pts/0 00:00:00 ps[[email protected] shellScript]$ kill -3 5119 #向子shell發送3訊號,即QUIT訊號[[email protected] shellScript]$ ps -a #子shell也未退出,說明QUIT訊號也被忽略 PID TTY TIME CMD 3822 pts/0 00:00:00 su 3830 pts/0 00:00:00 bash 3868 pts/0 00:00:00 su 3869 pts/0 00:00:00 bash 4037 pts/0 00:00:00 vim 4038 pts/0 00:00:00 vim 4418 pts/0 00:00:00 traploop.sh 4499 pts/0 00:00:00 sleep 5118 pts/0 00:00:00 subsig.sh 5119 pts/0 00:00:00 forever.sh 5128 pts/0 00:00:00 sleep 5129 pts/0 00:00:00 ps[[email protected] shellScript]$ kill 5118 #向父shell發送TERM訊號[[email protected] shellScript]$ ps -a #父shell仍未被殺掉 PID TTY TIME CMD 3822 pts/0 00:00:00 su 3830 pts/0 00:00:00 bash 3868 pts/0 00:00:00 su 3869 pts/0 00:00:00 bash 4037 pts/0 00:00:00 vim 4038 pts/0 00:00:00 vim 4418 pts/0 00:00:00 traploop.sh 4499 pts/0 00:00:00 sleep 5118 pts/0 00:00:00 subsig.sh 5119 pts/0 00:00:00 forever.sh 5133 pts/0 00:00:00 sleep 5134 pts/0 00:00:00 ps[[email protected] shellScript]$ kill 5119 #向子shell發送TERM訊號[[email protected] shellScript]$ Terminated #子shell立刻被終止You want to kill me! #並列印出父shell對TERM訊號的相應資訊[1]+ Exit 143 ./subsig.sh #父shell隨著子shell的終止而終止[[email protected] shellScript]$
Linux shell 訊號繼承