Initial version of phier.
[profile.git] / phier
1 #!/bin/bash
2
3 function find_parent() {
4   child="$1"; shift
5   top="$1"; shift
6
7   cmd=$(ps -o comm= -p $child)
8   pid=$(ps -o pid= -p $child)
9   ppid=$(ps -o ppid= -p $child)
10
11 # echo >&2 "Finding from $child ($top) $pid/$ppid/$cmd"
12
13   if [ -z "$pid" ]; then
14     echo >&2 "Can't find PID $child!"
15     return 1
16   fi
17
18   if [ ! -z "$top" ]; then
19     if [ "$cmd" = "$top" ]; then
20       echo $child
21       return 0
22     fi
23   fi
24
25   if [ $ppid = 1 ]; then
26     echo $pid
27     return 0
28   fi
29
30   find_parent $ppid $top
31   return $?
32 }
33
34 if [ $# -lt 1 ]; then
35   echo >&2 "phier: Print process hierarchy for a process."
36   echo >&2 "Usage: phier <pid> [<search>]"
37   echo >&2 "Notes: If a search term is given the hierarchy will stop after finding a"
38   echo >&2 "       process matching that search term."
39   echo >&2 "Example: phier $$ sshd"
40   exit 1
41 fi
42
43 parent=$(find_parent ${1+"$@"})
44 if [ $? = 0 ]; then
45   pstree -ulap $parent
46 else
47   exit 1
48 fi