When managing processes on Linux, there are times you may need to identify child processes spawned by a specific parent process. This can be especially useful when debugging, monitoring, or terminating processes. This tutorial explains how to get child processes of specified process on Linux.
We'll use two scripts: one representing the parent process and another representing the child processes. Create the child script (child.sh
):
printf "while :; do :; done" > child.sh && chmod a+x child.sh
This script runs an infinite loop. Create the parent script (parent.sh
):
printf "./child.sh &\n./child.sh &\nwhile :; do :; done" > parent.sh && chmod a+x parent.sh
The parent script spawns two child processes and then itself enters an infinite loop. Start the parent process:
./parent.sh &
Output example: [1] 72790
.
1. pgrep command
The pgrep
command is a simple way to list child processes by their parent process ID:
pgrep -P 72790
This will output the PIDs of the child processes. For example:
72791
72792
2. pstree command
The pstree
command provides a hierarchical view of processes, showing the parent-child relationships clearly:
pstree -p 72790
Example output:
bash(72790)─┬─bash(72791)
└─bash(72792)
3. ps command
The ps
command is highly customizable and can be used to display detailed process information. To list child processes of the parent process, run the command:
ps --ppid 72790 -o pid,ppid,cmd
This command outputs a table of child processes:
PID PPID CMD
72791 72790 bash
72792 72790 bash
Note: The command to terminate child processes and parent process:
pkill -9 -P 72790 && kill -9 72790
Leave a Comment
Cancel reply