0

Is it correct that

  • pstree <pid> will output all the descendant processes of the given process

  • pstree -s <pid> will output all the descendant processes and ancestry processes of the given process

How can I get only the ancestry processes of a given process?

Thanks.

Tim
  • 101,790

2 Answers2

5

You can always walk the ancestry tree by hand using ps -o ppid=:

#! /bin/bash -
pid=${1?Please give a pid}
while
  [ "$pid" -gt 0 ] &&
    read -r ppid name < <(ps -o ppid= -o comm= -p "$pid")
do
  printf '%s\n' "$pid $name"
  pid=$ppid
done

Or to avoid running ps several times:

#! /bin/sh -
pid=${1?Please give a pid}
ps -Ao pid= -o ppid= -o comm= |
  awk -v p="$pid" '
    {
      pid = $1; ppid[pid] = $2
      sub(/([[:space:]]*[[:digit:]]+){2}[[:space:]]*/, "")
      name[pid] = $0
    }
    END {
      while (p) {
        print p, name[p]
        p = ppid[p]
      }
    }'
  • Thanks. (1) Is there some reason to use bash in the shebang of one script, and sh in the other? (2) Is there some difference between double dash and single dash https://unix.stackexchange.com/questions/459208/signal-the-end-of-option-arguments-double-dashes-vs-single-dash – Tim Jul 29 '18 at 17:43
  • @Tim, for (1) that's because <(...) is not sh syntax. That will only work in zsh, bash or recent versions of ksh93. ... | read -r pid name would only work in zsh or ksh93, here-doc+cmdsubst would be sh but more convoluted and less efficient. For (2), see Why the "-" in the "#! /bin/sh -" shebang? – Stéphane Chazelas Jul 29 '18 at 18:56
  • Thanks. (1) Can both scripts use bash in shebang? – Tim Jul 29 '18 at 19:01
2

You can try following, I found it in Linux man page : -h This highlight the current process and its ancestors. -n This will sort processes with the same ancestor by PID instead of by name.

Nur
  • 131
  • 4