Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill a Java process started by a script if script was terminated via CTRL + C?

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?

like image 313
XåpplI'-I0llwlg'I - Avatar asked Dec 13 '25 07:12

XåpplI'-I0llwlg'I -


1 Answers

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
like image 105
OmegaOuter Avatar answered Dec 14 '25 21:12

OmegaOuter



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!