Shell – How to get the PID of a sub process across to the parent process in a bash shell script

linuxprocessshell-script

My shell script is as following:

#!/bin/bash
./process1 #It will create a sub process: sub_process1
while [ condition ]; do
    break
done
kill -9 process1 and sub_process1

In my script, it will create a process: process1. The process1 will create a sub process: sub_process1.
Before the script finish, it need to kill the process1 and sub_process1.
It is easy to kill the process1 as it will write the PID into a file. But the sub_process1 will not. As the sub_process1 is a third-party component, I can't touch the source code.
There is a solution that can get the PID of sub_process1:

  1. Enumerate all processes with the command ps aux;
  2. Get PPID(parent process ID) for each process with the command ps -f [PID]. If the PPID is equal to the PID of process1, the process must be sub_process1.
    The above solution is a bit complicate. Is there a simple solution that can get sub process ID?
    Thanks a lot.

Best Answer

Since you tagged this as Linux: pgrep / pkill to the rescue:

PID_OF_SUB_PROCESS1=$( pgrep -P $PID_OF_PROCESS1 )
pkill -P $PID_OF_PROCESS1
Related Question