Command pstree PID
can show all subprocess information of the process specified by PID
. However, I also want to know all parent process information of the process PID
, how can I get it?
An example:
init |- parent_process | `- current_process | |- subprocess_1 | `- subprocess_2 `- other_process
What I want is when I run pstree current_process_pid
, I want to get below output:
init `- parent_process `- current_process |- subprocess_1 `- subprocess_2
When I run pstree subprocess_1_pid
, it will output:
init `- parent_process `- current_process `- subprocess_1
Type the simply “pstree” command with the “-p” option in the terminal to check how it displays all running parent processes along with their child processes and respective PIDs. It shows the parent ID along with the child processes IDs.
The pstree command lists all of the direct and indirect child processes in a tree structure. We can also find the child processes of a parent process in the /proc file system recursively. We also supplied a shell script for automatically finding all of the child processes using the /proc file system.
How to get a parent PID (PPID) from a child's process ID (PID) using the command-line. e.g. ps -o ppid= 2072 returns 2061 , which you can easily use in a script etc. ps -o ppid= -C foo gives the PPID of process with command foo . You can also use the old fashioned ps | grep : ps -eo ppid,comm | grep '[f]oo' .
pstree is a Linux command that shows the running processes as a tree. It is used as a more visual alternative to the ps command. The root of the tree is either init or the process with the given pid. It can also be installed in other Unix systems.
# With my psmisc 22.20:
pstree -p -s PID
Maybe if with ps -ef:
awk -vPID=$1 '
function getParent ( pid ) {
if (pid == "" || pid == "0") return;
while ("ps -ef | grep "pid | getline) {
if ($2 == pid) {
print $8"("$2") Called By "$3;
getParent($3);
break;
}
}
close ("ps -ef")
}
BEGIN { getParent(PID) }
'
This is ugly assuming ps output column and order. Actually one single run of ps -ef contains all info needed. This don't worth the time, I still recommend updating psmisc, it won't hurt.
EDIT: A mimic using single run ps -ef:
ps -ef | awk -vPID=$1 '
function getpp ( pid, pcmd, proc ) {
for ( p in pcmd ) {
if (p == pid) {
getpp(proc[p], pcmd, proc);
if (pid != PID) printf("%s(%s)───", pcmd[pid], pid);
}
}
}
NR > 1 {
# pid=>cmd
pcmd[$2] = $8;
# pid=>Parent
pproc[$2] = $3;
}
END {
getpp(PID, pcmd, pproc);
printf "\n";
system("pstree -p "PID);
}'
I found laps
options mentioned by @haridsv (pstree -laps <pid>
) being a solution. It was a bit verbose for me though, so I'd stick to a shorter aps
output.
To get the process tree of the current process (its ID is $$
in Bash):
pstree -aps $$
That prints the process tree like this:
systemd,1
└─kitty,86739
└─bash,86742
└─pstree,86904 -aps 86742
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With