3

I have the following script1.sh:

#!/bin/bash

trap 'echo "Exit signal detected..."; kill %1' 0 1 2 3 15

./script2.sh & #starts a java app
./script3.sh #starts a different java app

When I do CTRL + C, it terminates script1.sh, but the Java Swing app started by script2.sh still stays open. How come it doesn't kill it?

XåpplI'-I0llwlg'I -
  • 21,649
  • 28
  • 102
  • 151
  • possible duplicate of [Bash: How do I make sub-processes of a script be terminated, when the script is terminated?](http://stackoverflow.com/questions/7817637/bash-how-do-i-make-sub-processes-of-a-script-be-terminated-when-the-script-is) – Thilo Jun 25 '12 at 06:41
  • also: http://stackoverflow.com/questions/360201/kill-background-process-when-shell-script-exit – Thilo Jun 25 '12 at 06:41
  • I've tried both. Neither kills an actual Java app if it is running... – XåpplI'-I0llwlg'I - Jun 25 '12 at 06:55

2 Answers2

1

I think something like this could work for you. However, as @carlspring mentioned you better have something similar in each script so you can catch the same interrupt and kill any missing child process.

Take whatever it

#!/bin/bash

# Store subproccess PIDS
PID1=""
PID2=""

# Call whenever Ctrl-C is invoked
exit_signal(){
    echo "Sending termination signal to childs"
    kill -s SIGINT $PID1 $PID2
    echo "Childs should be terminated now"
    exit 2
}

trap exit_signal SIGINT

# Start proccess and store its PID, so we can kill it latter
proccess1 &
PID1=$!
proccess2 &
PID2=$!

# Keep this process open so we can close it with Ctrl-C
while true; do
    sleep 1
done
OmegaOuter
  • 375
  • 1
  • 11
0

Well, if you're starting the script in background mode (using &), it's normal behavior for it to keep executing after the invoking script has exited. You need to get the process id of the second script by storing echo $$ to a file. Then make the respective script have a stop command which kills this process, when you invoke it.

carlspring
  • 31,231
  • 29
  • 115
  • 197