trap命令用来捕捉特定信号,并且指定捕获该信号的行为。
格式:
trap commands signals
SIGHUP会在以下3种情况下被发送给相应的进程:
1、终端关闭时,该信号被发送到和shell进程同一个进程组的进程。
2、session首进程退出时,该信号被发送到该session中的前台进程组中的每一个进程
3、若父进程退出导致进程组成为孤儿进程组,且该进程组中有进程处于停止状态(收到SIGSTOP或SIGTSTP信号),该信号会被发送到该进程组中的每一个进程。
-
#!/bin/bash
-
-
count=1
-
cat /dev/null > ~/test/shell/signal/wgw_hup
-
cat /dev/null > ~/test/shell/signal/recv_hup
-
trap "echo 'SIGHUP signal' > ~/test/shell/signal/wgw_hup" SIGHUP
-
while [ $count -le 10 ]
-
do
-
echo "Loop #$count" >> ~/test/shell/signal/recv_hup
-
sleep 5
-
count=$[ $count + 1 ]
-
done
-
-
echo "exiting....." >> ~/test/shell/signal/recv_hup
1.执行脚本
sh sighup.sh
操作:关闭终端
结果:
-
gwwu@hz-dev2.wgw.com:~/test/shell/signal>more recv_hup
-
Loop #1
-
Loop #2
-
Loop #3
-
Loop #4
-
Loop #5
-
Loop #6
-
Loop #7
-
Loop #8
-
Loop #9
-
Loop #10
-
exiting.....
-
gwwu@hz-dev2.wgw.com:~/test/shell/signal>more wgw_hup
-
SIGHUP signal
-
gwwu@hz-dev2.wgw.com:~/test/pipe>ps -ef | grep sighup
-
gwwu 8175 7943 0 11:18 pts/16 00:00:00 sh sighup.sh
-
gwwu 8184 30681 0 11:18 pts/7 00:00:00 grep sighup
-
gwwu@hz-dev2.wgw.com:~/test/pipe>ps -ef | grep sighup-----------关闭终端后,原先的进程变成daemon进程。
-
gwwu 8175 1 0 11:18 ? 00:00:00 sh sighup.sh
-
gwwu 8189 30681 0 11:18 pts/7 00:00:00 grep sighup
2. 执行脚本
sh sighup.sh &
操作:关闭终端
结果:
-
gwwu@hz-dev2.aerohive.com:~/test/shell/signal>more recv_hup
-
Loop #1
-
Loop #2
-
Loop #3
-
Loop #4
-
Loop #5
-
Loop #6
-
Loop #7
-
Loop #8
-
Loop #9
-
Loop #10
-
exiting.....
-
gwwu@hz-dev2.aerohive.com:~/test/shell/signal>more wgw_hup
-
SIGHUP signal
gwwu@hz-dev2.wgw.com:~/codes/istanbul_2_9>ps -ef | grep sighup
gwwu 26204 23029 0 11:21 pts/3 00:00:00 sh sighup.sh
gwwu 26245 26218 0 11:21 pts/6 00:00:00 grep sighup
gwwu@hz-dev2.wgw.com:~/codes/istanbul_2_9>ps -ef | grep sighup----------关闭终端后shell进程仍然存在
gwwu 26204 1 0 11:21 ? 00:00:00 sh sighup.sh
gwwu 26249 26218 0 11:21 pts/6 00:00:00 grep sighup
gwwu@hz-dev2.wgw.com:~/codes/istanbul_2_9>ps -ef | grep sighup
gwwu 26204 1 0 11:21 ? 00:00:00 sh sighup.sh
gwwu 26251 26218 0 11:21 pts/6 00:00:00 grep sighup
3.将脚本中的trap行去掉
-
#!/bin/bash
-
-
count=1
-
cat /dev/null > ~/test/shell/signal/wgw_hup
-
cat /dev/null > ~/test/shell/signal/recv_hup
-
while [ $count -le 10 ]
-
do
-
echo "Loop #$count" >> ~/test/shell/signal/recv_hup
-
sleep 5
-
count=$[ $count + 1 ]
-
done
-
-
echo "exiting....." >> ~/test/shell/signal/recv_hup
执行sh sighup.sh 和sh sighup.sh &
关闭终端后进程直接退出
执行nohup sh sighhup.sh
关闭终端后进程仍然执行,直到进程结束。
阅读(1195) | 评论(0) | 转发(0) |