Initial version of phier.
authorIain Patterson <me@iain.cx>
Wed, 3 Oct 2007 07:14:31 +0000 (07:14 +0000)
committerIain Patterson <me@iain.cx>
Wed, 3 Oct 2007 07:14:31 +0000 (07:14 +0000)
git-svn-id: https://svn.cambridge.iain.cx/profile/trunk@74 6be0d1a5-5cfe-0310-89b6-964be062b18b

phier [new file with mode: 0755]

diff --git a/phier b/phier
new file mode 100755 (executable)
index 0000000..f2aad9f
--- /dev/null
+++ b/phier
@@ -0,0 +1,48 @@
+#!/bin/bash
+
+function find_parent() {
+  child="$1"; shift
+  top="$1"; shift
+
+  cmd=$(ps -o comm= -p $child)
+  pid=$(ps -o pid= -p $child)
+  ppid=$(ps -o ppid= -p $child)
+
+# echo >&2 "Finding from $child ($top) $pid/$ppid/$cmd"
+
+  if [ -z "$pid" ]; then
+    echo >&2 "Can't find PID $child!"
+    return 1
+  fi
+
+  if [ ! -z "$top" ]; then
+    if [ "$cmd" = "$top" ]; then
+      echo $child
+      return 0
+    fi
+  fi
+
+  if [ $ppid = 1 ]; then
+    echo $pid
+    return 0
+  fi
+
+  find_parent $ppid $top
+  return $?
+}
+
+if [ $# -lt 1 ]; then
+  echo >&2 "phier: Print process hierarchy for a process."
+  echo >&2 "Usage: phier <pid> [<search>]"
+  echo >&2 "Notes: If a search term is given the hierarchy will stop after finding a"
+  echo >&2 "       process matching that search term."
+  echo >&2 "Example: phier $$ sshd"
+  exit 1
+fi
+
+parent=$(find_parent ${1+"$@"})
+if [ $? = 0 ]; then
+  pstree -ulap $parent
+else
+  exit 1
+fi