trap command signal
trap捕获信号(软中断),command一般是linux命令 若为' '表示发生陷阱时为空指令,'-'表示发生陷阱时采用缺省指令
signal:
HUP(1) 挂起;一般因终端掉线或用户退出而引发
INT(2)中断;一般因按下"Ctrl+C"组合键引发
QUIT(3) 退出;一般因按下"Ctrl+\"组合键引发
ABRT(6) 异常终止;一般因某些严重的执行错误而引发
ALRM(14) 闹钟;一般是超时时钟到来而引发
TREM(15) 终止;一般是由系统在关机时发出
trap只是对信号的操作进行关联(安装信号)
1 #! /bin/bash 2 3 trap "rm -f tmp$$;exit 0" 2 3 #$$表示的是当前进程号,捕获2,3号信号 4 touch tmp$$ 5 sleep 60
下面看一个锁屏程序:
1#! /bin/bash 2 3 trap "nice_try" 2 3 15 4 TTY=`pwd` 5 6 nice_try() 7 { 8 echo -e "\nNice try,the terminal stays locked" 9 } 10 11 #stty -echo #输入的密码不回显 12 13 echo -n "Enter your password to lock $TTY: " 14 read PASSWORD 15 clear 16 echo -n "Enter you password to unlock $TTY: " 17 while : 18 do 19 read RESPONSE 20 if [ "$RESPONSE" = "$PASSWORD" ];then 21 echo "unlocking..." 22 break 23 fi 24 clear 25 echo "wrong password and terminal is locked..." 26 echo -n "Enter your password to unlock $TTY: " 27 done 28 29 #stty echo #恢复回显