Kill bash script foreground children when a signal

2019-04-19 14:52发布

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

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

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

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.

EDIT: 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?

7条回答
兄弟一词,经得起流年.
2楼-- · 2019-04-19 15:34

I'm not sure I fully get your point, but here's what I tried and the process seems to be able to manage the trap (call it trap.sh):

#!/bin/bash

trap "echo trap activated" TERM INT
echo begin
time sleep 60
echo end

Start it:

./trap.sh &

And play with it (only one of those commands at once):

kill -9 %1
kill -15 %1

Or start in foreground:

./trap.sh

And interrupt with control-C.

Seems to work for me. What exactly does not work for you?

查看更多
登录 后发表回答