问题
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, give below process:
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
Thanks in advance
回答1:
# 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);
}'
回答2:
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.
来源:https://stackoverflow.com/questions/12852023/how-to-get-all-parent-processes-and-all-subprocesses-by-pstree