eaa1b14037709c10eab764ca0ffdb317e5f8f32e
[profile.git] / phier
1 #!/bin/bash
2 #
3 # $Id$
4 #
5 # phier: Show process tree incorporating a process.
6 # Notes: phier functions similarly (but not identically) to Solaris ptree.
7 # Usage: phier [options] <pid>
8 # Options: -s <search>   Stop hierarchy at this process name.
9 # Example: phier -s sshd $$
10 #
11
12 function find_parent() {
13   child="$1"; shift
14   top="$1"; shift
15
16   if [ -z "$child" ]; then
17     echo >&2 "No child to find."
18     return 1
19   fi
20
21   cmd=$(ps -o comm= -p $child)
22   pid=$(ps -o pid= -p $child)
23   ppid=$(ps -o ppid= -p $child)
24
25 # echo >&2 "Finding from $child ($top) $pid/$ppid/$cmd"
26
27   if [ -z "$pid" ]; then
28     echo >&2 "Can't find PID $child!"
29     return 1
30   fi
31
32   if [ ! -z "$top" ]; then
33     if [ "$cmd" = "$top" ]; then
34       echo $child
35       return 0
36     fi
37   fi
38
39   if [ $pid = 1 -o $ppid = 1 ]; then
40     echo $pid
41     return 0
42   fi
43
44   find_parent $ppid $top
45   return $?
46 }
47
48 # Parse arguments.
49 top=
50 while getopts ":s:" opt; do
51   case $opt in
52     s) top="$1";;
53   esac
54 done
55 shift $((OPTIND-1))
56
57 if [ $# -lt 1 ]; then
58   echo >&2 "phier: Print process hierarchy for a process."
59   echo >&2 "Usage: phier [options] <pid>"
60   echo >&2 "Options: -s <search>   Stop hierarchy at this process name."
61   echo >&2 "Example: phier -s sshd $$"
62   exit 1
63 fi
64
65 parent=$(find_parent "$1" "$top")
66 if [ $? = 0 ]; then
67   pstree -ulap $parent
68 else
69   exit 1
70 fi