1

I have scriptA which will execute another script which will startup in the background. Now I need to make sure that when I kill scriptA (cmd+c) that the background processes are also killed.

#!/bin/bash
echo "This script is about to run another script."
  sh ../processes/processb/bin/startserver.sh &
 FOO_PID=$!
 echo "This script has just run another script." $FOO_PID

This script executes fine, but once I press cmd+c and do a 'ps' command on FOO_PID value , that process still exists. What am I doing wrong?

UPDATE-----------

So I tried out below code, but still scriptC's process is not getting killed. I think it just only terminates scriptA ( parent) when pressed ctrl+c and therefore trap command does not get executed?

     #!/bin/bash

echo "This script is about to run another script."

   ../common/samples/bin/scriptC.sh &
 mypid=$!
kill -0 "$mypid" && echo "My process is still alive."

echo "This script has just run another script." $mypid

trap "kill $mypid && kill $$" INT
user2894296
  • 590
  • 1
  • 10
  • 20

1 Answers1

3

Add a trap for SIGINT:

trap "kill $FOO_PID && kill $$" INT

or for any sort of exiting, handle the pseudo signal EXIT:

trap "kill $FOO_PID && kill $$" EXIT
heemayl
  • 39,294
  • 7
  • 70
  • 76
  • Thanks heemayl, out of curiosity shouldn't it anyway be killed since I have not used 'nohup' here? – user2894296 Jan 09 '17 at 06:30
  • @user2894296 It's a long story. In a nutshell, the backgrounded process is now running in it's own process group, with the PID being the PGID. – heemayl Jan 09 '17 at 06:32