Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kill bash script foreground children when a signal comes

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?

like image 286
Arkaitz Jimenez Avatar asked Nov 23 '10 22:11

Arkaitz Jimenez


People also ask

How do you stop a foreground process in Linux?

CTRL+Z – This keystroke will stop the running process. CTRL+C – This keystroke will kill the running process and free up memory in RAM.

Which control signal will suspend a foreground command?

A job running in the foreground can be stopped by typing the suspend character (Ctrl-Z).

Does Ctrl C kill background process?

When you press ctrl+c , you are sending an interrupt signal to the foreground process, and it will not affect the background process. In order to kill the background process, you should use the kill command with the PID of the most recent background process, which could be obtained by $! .

What is $! In Bash?

$! bash script parameter is used to reference the process ID of the most recently executed command in background. $$ $$ is used to reference the process ID of bash shell itself.


1 Answers

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?

like image 111
asoundmove Avatar answered Oct 01 '22 14:10

asoundmove