bash 中的 trap 和 wait

2120阅读 0评论2015-07-23 seaquester
分类:LINUX

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).

上一篇:在Linux启动时加载内核模块
下一篇:如何在编译动态链接库时报告未定义符号的错误