Posted on 2010-03-28 17:42
Prayer 閱讀(3535)
評論(0) 編輯 收藏 引用 所屬分類:
Shell
一. trap捕捉到信號之后,可以有三種反應(yīng)方式:
(1)執(zhí)行一段程序來處理這一信號
(2)接受信號的默認(rèn)操作
(3)忽視這一信號
二. trap對上面三種方式提供了三種基本形式:
第一種形式的trap命令在shell接收到signal list清單中數(shù)值相同的信號時,將執(zhí)行雙
引號中的命令串。
trap 'commands' signal-list
trap "commands" signal-list
為了恢復(fù)信號的默認(rèn)操作,使用第二種形式的trap命令:
trap signal-list
第三種形式的trap命令允許忽視信號
trap " " signal-list
注意:
(1) 對信號11(段違例)不能捕捉,因?yàn)閟hell本身需要捕捉該信號去進(jìn)行內(nèi)存的轉(zhuǎn)儲。
(2) 在trap中可以定義對信號0的處理(實(shí)際上沒有這個信號), shell程序在其終止(如
執(zhí)行exit語句)時發(fā)出該信號。
(3) 在捕捉到signal-list中指定的信號并執(zhí)行完相應(yīng)的命令之后, 如果這些命令沒有
將shell程序終止的話,shell程序?qū)⒗^續(xù)執(zhí)行收到信號時所執(zhí)行的命令后面的命令,這樣將
很容易導(dǎo)致shell程序無法終止。
另外,在trap語句中,單引號和雙引號是不同的,當(dāng)shell程序第一次碰到trap語句時,
將把commands中的命令掃描一遍。此時若commands是用單引號括起來的話,那么shell不會
對commands中的變量和命令進(jìn)行替換, 否則commands中的變量和命令將用當(dāng)時具體的值來
kill -l可以列出系統(tǒng)的信號
通常我們需要忽略的信號有四個,即:HUP, INT, QUIT, TSTP,也就是信號1, 2, 3, 24
使用這樣的語句可以使這些中斷信號被忽略:
trap "" 1 2 3 24 或 trap "" HUP INT QUIT TSTP
用 trap :1 2 3 24 或 trap HUP INT QUIT TSTP使其回復(fù)默認(rèn)值。
用stty -a可以列出中斷信號與鍵盤的對應(yīng),分別執(zhí)行上面的命令后,運(yùn)行
tail -f /etc/passwd, 然后嘗試用鍵盤中斷,試試兩種情況(默認(rèn)和忽略)下有何不同。
更方便的是我們可以用在shell中用trap定義我們自己的信號處理程序
#!/bin/bash
#scriptname: trapping
#can use the singnal numbers of bash abbreviations seen
#below. Cannot use SIGINT ,SIGOUIT ,etc
trap 'echo Control-c will not terminate $0. ' INT
trap 'echo Control-\ will not terminate $0. ' QUIT
trap 'echo Control-Z will not terminate $0. ' TSTP
echo "Enter any string after the prompt. When you are ready to exit ,type \"stop\"."
while true
do
echo -n "Go ahead ...>"
read
if [[ $reply==[sS]top ]]
then
break
fi
done