信号
- linux通过信号来在运行在系统上的进程之间通信也可以通过信号来控制shell脚本的运行
(1)捕捉信号:trap命令
- 常用信号 ctrl+c(终止进程) ctrl+z(暂停进程,打入后台)
[root@server ~]# trap "echo westos" 2
[root@server ~]# ^Cwestos
(2)列出中断信号与键盘的关系
[root@server ~]# stty -a
speed 38400 baud; rows 24; columns 80; line = 0;
intr = ^C; quit = ^\; erase = ^?; kill = ^U; eof = ^D; eol = <undef>;
eol2 = <undef>; swtch = <undef>; start = ^Q; stop = ^S; susp = ^Z; rprnt = ^R;
werase = ^W; lnext = ^V; flush = ^O; min = 1; time = 0;
-parenb -parodd -cmspar cs8 -hupcl -cstopb cread -clocal -crtscts
-ignbrk -brkint -ignpar -parmrk -inpck -istrip -inlcr -igncr icrnl ixon -ixoff
-iuclc -ixany -imaxbel -iutf8
opost -olcuc -ocrnl onlcr -onocr -onlret -ofill -ofdel nl0 cr0 tab0 bs0 vt0 ff0
isig icanon iexten echo echoe echok -echonl -noflsh -xcase -tostop -echoprt
echoctl echoke
(3)信号屏蔽
[root@server ~]# trap "" 2 ##信号屏蔽
[root@server ~]# trap : 2 ##恢复信号
(4)脚本形式:
#!/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 2
count=$[ $count + 1 ]
done
echo "This is the end of the script~"
trap - 2 ##恢复
echo "I just removed the trap"
(5)捕捉脚本的退出
[root@server ~]# cat trap.sh
trap "echo ByeBye~" EXIT
count=1
while [ $count -le 5 ]
do
echo "Loop #$count"
sleep 2
count=$[ $count + 1 ]
done
[root@server ~]# sh trap.sh
Loop #1
Loop #2
Loop #3
^CByeBye~
(6)练习
- 执行脚本时,使用ctrl+c可以将/tmp/westos下建立的文件都删除掉
#!/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