How to get all parent processes and all subprocesses on `pstree`

The pstree PID command can display all information about the process subprocess specified by the PID . However, I also want to know all the parent information of the PID process process, how can I get it?

Example, follow the process described below:

  init
 | - parent_process
 |  `- current_process
 |  | - subprocess_1
 |  `- subprocess_2
 `- other_process

What I want, 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

+6
source share
2 answers
 # 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 an ugly assumption about ps output column and order. In fact, one ps -ef run contains all the necessary information. It is not worth the time, I still recommend updating psmisc, it will not hurt.

EDIT: imitation using the 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); }' 
+9
source

I found the laps options mentioned by @haridsv ( pstree -laps <pid> ) as a solution. This was a bit verbose for me, so I stick to the shorter aps output.

+2
source

Source: https://habr.com/ru/post/927526/


All Articles