Chinaunix首页 | 论坛 | 博客
  • 博客访问: 586256
  • 博文数量: 50
  • 博客积分: 4764
  • 博客等级: 上校
  • 技术积分: 597
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-18 09:00
个人简介

资深IT码农,擅长Linux、C/C++、bash

文章分类

全部博文(50)

文章存档

2015年(17)

2014年(2)

2011年(7)

2010年(4)

2009年(20)

分类: LINUX

2015-07-23 16:39:44

Bash中的 trap 和 wait

冷胜魁(Seaquester)
lengshengkui@outlook.com
2015-6-23

在Linux 的bash script中,我们可以用trap来安装一个signal handler来处理signal。但是,如果在script(比如main.sh)中有调用其它的script(比如sub.sh),那么,signal handler就可能不能及时的处理signal。必须要等到sub.sh 返回之后,main.sh中的signal handler才有机会被调用来处理signal。

如何避免出现这种状况,保证signal能及时的被处理呢?可以通过让sub.sh在后台运行来达到目的。

下面是一个例子:

main.sh(main.sh 将在后台执行 sub.sh,并通过wait来等待sub.sh结束。main.sh 如果收到SIGTERM signal,将会发送SIGTERM到sub.sh

点击(此处)折叠或打开

  1. #!/bin/sh
  2. term_exit()
  3. {
  4.    echo "main: terminated"
  5.    pkill sub.sh
  6.    exit 1
  7. }
  8. trap term_exit TERM INT

  9. #Run sub.sh and wait it.
  10. ./sub.sh &
  11. sub_pid=$!
  12. wait $sub_pid
  13. echo "main: DONE"
  14. exit 0

sub.sh(sub.sh将陷入一个循环,收到SIGTERM才会退出)

点击(此处)折叠或打开

  1. #!/bin/sh
  2. term_exit()
  3. {
  4.    echo "sub: terminated"
  5.    exit 1
  6. }
  7. trap term_exit TERM
  8. while true ;do
  9. echo -n "."
  10. sleep 1
  11. done
  12. echo "sub: DONE"
  13. exit 0
上面的例子的使用方法如下:

(1) 运行 main.sh
$ ./main.sh

(2) 发送一个 TERM signal 到 main.sh
$ pkill main.sh
main.sh

参考资料:

Normally, bash will ignore any signals while a child process is executing. Starting the server with & will background it into the shell's job control system, with $! holding the server's PID (to be used with wait and kill). Calling wait will then wait for the job with the specified PID (the server) to finish, or for any signals to be fired.

When the shell receives SIGTERM (or the server exits independently), the wait call will return (exiting with the server's exit code, or with the signal number + 127 if a signal was received). Afterward, if the shell received SIGTERM, it will call the _term function specified as the SIGTERM trap handler before exiting (in which we do any cleanup and manually propagate the signal to the server process using kill).

阅读(1806) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~