信号到来时杀死bash脚本前台孩子 [英] Kill bash script foreground children when a signal comes

查看:64
本文介绍了信号到来时杀死bash脚本前台孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将fastcgi应用程序包装在bash脚本中,如下所示:

I am wrapping a fastcgi app in a bash script like this:

#!/bin/bash
# stuff
./fastcgi_bin
# stuff

因为bash仅在前景脚本结束时执行信号陷阱,所以我不能只是kill -TERM scriptpid,因为fastcgi应用程序将保持活动状态.
我尝试将二进制文件发送到后台:

As bash only executes traps for signals when the foreground script ends I can't just kill -TERM scriptpid because the fastcgi app will be kept alive.
I've tried sending the binary to the background:

#!/bin/bash
# stuff
./fastcgi_bin &
PID=$!
trap "kill $PID" TERM
# stuff

但是,如果我这样做,显然stdin和stdout不能正确重定向,因为它没有与lighttpds mod_fastgi连接,前景版本确实可以工作.

But if I do it like this, apparently the stdin and stdout aren't properly redirected because it does not connect with lighttpds mod_fastgi, the foreground version does work.

我一直在研究问题,这是因为在后台启动程序时bash将/dev/null重定向到stdin,所以避免这种情况的任何方法都应解决我的问题问题.

I've been looking at the problem and this happens because bash redirects /dev/null to stdin when a program is launched in the background, so any way of avoiding this should solve my problem as well.

关于如何解决此问题的任何提示?

Any hint on how to solve this?

推荐答案

我想到了一些选择:

  • 从shell脚本启动进程时,它们都属于同一进程组.杀死父进程将使子进程存活,因此应杀死整个进程组.这可以通过传递否定的PGID(进程组ID)来杀死,这与父级的PID相同. ej:kill -TERM -$PARENT_PID

不要以以下方式执行二进制文件: 一个孩子,但替换了脚本 exec处理.你失去了 事后执行的能力 但是,因为exec完全 替换父进程.

Do not execute the binary as a child, but replacing the script process with exec. You lose the ability to execute stuff afterwards though, because exec completely replaces the parent process.

不要杀死Shell脚本进程,而要杀死FastCGI二进制文件.然后,在脚本中,检查返回码并采取相应措施.例如:./fastcgi_bin || exit -1

Do not kill the shell script process, but the FastCGI binary. Then, in the script, examine the return code and act accordingly. e.g: ./fastcgi_bin || exit -1

取决于mod_fastcgi处理工作进程的方式,只有第二个选项才可行.

Depending on how mod_fastcgi handles worker processes, only the second option might be viable.

这篇关于信号到来时杀死bash脚本前台孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆