I have a Java GUI that starts a bash script that controls the running of other bash scripts, executes some system commands (e.g. cp and tar), and runs some executables. I want to add a "Stop" button that will kill all processes started by the aforementioned bash script. I know how to get the process IDs; the bash scripts are "echo'ing" $$ and the Java program is capturing that and killing those processes. Unfortunately, some of the scripts run cp's and other executables that won't die right away (e.g. the cp command is doing large copies). They will die eventually but I want to kill them now
. While figuring out how to get the PID's of these commands, I came across an issue when the "tee" command is involved.
Here is an illustration of what I'm talking about
:
When I run the following bash script, bbb.sh, which starts an external program, bbb.java:
Code:
#!/bin/bash
java bbb &
BBB_PID=$!
echo -e "BBB_PID ${BBB_PID}\n"
ps -a
This is what I see:
> bbb.sh
BBB_PID 10378
PID TTY TIME CMD
6720 pts/1 00:00:26 bluefish
10377 pts/1 00:00:00 bbb.sh
10378 pts/1 00:00:00 java
10379 pts/1 00:00:00 ps
I capture, via BBB_PID=$!, the PID of the java program. If killing PID 10377 doesn't kill the java program right away, then I can kill -9 10378 to finish off the java program.
Sometimes, though, the "tee" command is involved in the bash script and I notice the following:
Suppose now bbb.sh is as follows and I run it:
Code:
#!/bin/bash
java bbb | tee > out.txt &
BBB_PID=$!
echo -e "BBB_PID ${BBB_PID}\n"
ps -a
This is what I see:
> bbb.sh
BBB_PID 10397
PID TTY TIME CMD
6720 pts/1 00:00:27 bluefish
10395 pts/1 00:00:00 bbb.sh
10396 pts/1 00:00:00 java
10397 pts/1 00:00:00 tee
10398 pts/1 00:00:00 ps
In this case, the PID captured by BBB_PID=$! is that of the "tee" command not the "java bbb" command. This makes sense because, if I understand things correctly, $! contains the PID of the most recent background process, which in this case would be the "tee" command.
Now I can kill PID 10397, which causes PID 10396 to die with a pipe broken error. My concern is whether or not this is an okay thing to do. I have a bad feeling that this is not safe and may cause the whole process to crash.
I also noticed that everytime I tested this, the PID of the "tee" command was one greater than the PID of the "java bbb" command. If that is always going to be the case, then I could just kill the BBB_PID-1. But is that always going to be the case?
Any comments or suggestions?
Thanks times a million,
Bill