You can get the process ID of process
by running it as a background process.
./process1 &
pid1=$!
wait "$pid1"
The wait
command waits for process1
to exit (but not its subprocesses), like in your original script. Do note that in your original script, there's no process1
to kill at the end: the ./process1
command finishes only when process1
exits. It's possible that there is a child process of that process with the same name (i.e. the program may have called fork
but not execve
). If you want to continue running the script as soon as process1
itself has started, omit the wait
line.
If you have the pkill
command, it's a convenient way to kill all the children of a process. Note that the process must still be running, or must be a zombie, otherwise the children's parent process ID will be reset to 1 and you can't track them this way any longer. As long as you haven't called wait
in your script, the background process ID will remain valid.
./process1 &
pid1=$!
…
pkill -9 -P "$pid1"
kill -9 "$pid1"
Another way to track a process, its children, and their children recursively is to track the process group. The children of a process have the same process group unless they explicitly change it. On Linux, you can use the setsid
command to run a program in its own process group. The process group is identified by the process ID of the original process. To kill all the processes in a process group, pass the negative of the process group ID to kill
.
setsid ./process1 &
pgid1=$!
…
kill -9 "-$pgid1"
Yet another way to track processes is to make them open a file. This works as long as the processes don't close the files, so it might not work for a program that's intended to run as a daemon. Use the command fuser
to kill the processes that have the file open.
tmpfile=$(mktemp)
process1 <"$tmpfile"
…
fuser -k -9 "$tmpfile"