一 信号
linux通过信号来在运行在系统上的进程之间通信;也可以通过信号来控制shell脚本的运行
1 ##进程重新加载配置
2 ##删除进程在内存中的数据
3 ##删除鼠标在内存中的数据
9 ##强行结束单个进程(不能被阻塞)
15 ##正常关闭进程 (可能被阻塞)
18 ##运行暂停的进程
19 ##暂停某个进程 (不能被阻塞)
20 ##把进程号打入后台
man 7 signal ##查看信号详细信息
1)捕捉信号:trap命令
#常用信号 ctrl+c(终止进程) ctrl+z(暂停进程)
[root@localhost mnt]# trap "echo hello" 2
[root@localhost mnt]# ^Chello
[root@localhost mnt]# ^Chello
2) 列出中断信号与键盘的关系
[root@localhost mnt]# 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"
~
执行结果:在脚本运行的过程中,ctrl+c是被禁止掉的,在脚本执行完毕后,crtl+c才被释放
[root@localhost mnt]# sh hhh.sh
This is a test script~
Loop #1
Loop #2
Loop #3
Loop #4
Loop #5
^CSorry!I have trapped Ctrl+C
Loop #6
^CSorry!I have trapped Ctrl+C
Loop #7
^CSorry!I have trapped Ctrl+C
Loop #8
^CSorry!I have trapped Ctrl+C
Loop #9
^CSorry!I have trapped Ctrl+C
Loop #10
This is the end of the script~
I just removed the trap
[root@localhost mnt]# ^C