Reputation: 2239
I have a shell script called Launcher.sh that gets executed by a java process. The java process internally uses ProcessBuilder to execute the bash script.
Inside the Launcher.sh, I have the following code
#!/bin/bash
trap "kill -- -$$ && kill -INT -$PID" SIGINT SIGTERM SIGKILL
bash Process_A.sh &
pid=$!
echo $pid
The Process_A script will spawn another child process called Process_B.
I want to kill both Process_A and Process_B when the Launcher.sh script receives a "kill" command or "kill -9" command from its parent the java process.
So I added a trap command to trap SIGINT, SIGTERM and SIGKILL interrupts. But when I do
kill $pid
it only kills Process_A but not the child Process_B. Both have the same PGID.
How can I kill all the child and grandchild processes spawned from my launcher.sh script correctly?
Here is an actual output of "ps j" before and after kill. Inside my script I do "dse spark" which inturn spawns a java process. I want this java process to be killed when the launcer script gets a kill signal
root@WeveJobs01:~# ps j
PPID PID PGID SID TTY TPGID STAT UID TIME COMMAND
2380 2381 2381 2281 pts/1 59265 S 0 0:00 /bin/bash
1 58917 58916 1152 pts/0 1236 S 0 0:00 bash /usr/bin/dse spark
58917 59041 58916 1152 pts/0 1236 Sl 0 0:07 /usr/lib/jvm/java-8-oracle/jre//bin/java -cp /etc/dse/spark/:/usr/share/dse/dse-
2381 59265 59265 2281 pts/1 59265 R+ 0 0:00 ps j
root@WeveJobs01:~# kill 58917
root@WeveJobs01:~# ps j
PPID PID PGID SID TTY TPGID STAT UID TIME COMMAND
1152 1235 1235 1152 pts/0 1236 S 0 0:00 sudo -s
1235 1236 1236 1152 pts/0 1236 S+ 0 0:00 /bin/bash
1 59041 58916 1152 pts/0 1236 Sl 0 0:23 /usr/bin/java -cp /etc/dse/spark/:/usr/share/dse/dse-
2381 59513 59513 2281 pts/1 59513 R+ 0 0:00 ps j
I tried this..and when I do "kill pid" where pid is that of the script. I get segmentation fault as it goes to infinite loop
trap 'echo "Kill All"; kill -TERM -$$' TERM INT
bash child.sh &
PID=$!
wait $PID
trap - TERM INT
wait $PID
EXIT_STATUS=$?
Upvotes: 4
Views: 3506
Reputation: 2239
I need to reset kill -term in the trap statement to prevent infinite loop. This worked
trap "trap -INT && kill -- -$$"
Upvotes: 2