#!/bin/sh # # Author: Andy Welter # www.the-welters.com # January 15, 2000 # # Display a parent child relationship for a process or all processes # on a system. # # This script uses recursive calls to itself in a bourne shell script # which is kinda cool, but is really inefficient. # # It takes advantage of the "-o" option on the PS command to put # the PS output into a more easily parsed format and this also # makes it more portable between Unix flavors. Linux does not # support this option, so unfortunately it doesn't work on Linux. # lookup_ancestors () { # # Find parent of current process, then recursively call this # script to display it's line of anscestors. # # Note that Orphan processes show pid 1 as their parent. # PID=$1 PROC=`cat $FILE | grep "^$PID "` PPID=`echo "$PROC" | (read pid ppid user args;echo $ppid)` if [ -n "$PPID" ]; then if [ $PID -ne 0 ]; then $0 -p $PPID fi fi } lookup_descendents () { # # Find list of children of the current process, and recursively # call this script for each of the children found to display # their children. cat $FILE | grep " $1 " | \ while read PID PPID USER ARGS; do if [ "$PID" != "$PPID" ]; then $0 -c $PID "$indent" fi done } display_process () { # # display the ps info of the indicated process. # (can be used for parents or children) # $1 is the pid to display # $indent is the amount of indentation to display before the process # cat $FILE | grep "^$1 " | while read PID PPID USER ARGS; do echo "$indent$USER $PID $PPID $ARGS" done } step=" " PS="ps -ea -o pid -o ppid -o user -o args" if [ "$1" = "-p" ]; then # # look up parent pid then display the current process. # anscestors will be in oldest to newest order. # # don't bother indenting for parents. #indent="$3" lookup_ancestors $2 #indent="$indent$step" display_process $2 elif [ "$1" = "-c" ]; then # # lookup child pid # indent=$3 display_process $2 indent="$indent$step" lookup_descendents $2 else if [ "$1" = "" ]; then START=0 else START=$1 fi # # This is the initial call to the script. # Display ancestors and descendents # # echo echo "=================" echo "= Looking up information for process $START" echo "=================" # Get the output to ps and normalize it's output FILE=/tmp/pstree.$$ export FILE indent="" $PS | tail +2 | sed 's/^ *//g' > $FILE display_process $START # echo echo "=================" echo "= Ancestors of process $START" echo "=================" lookup_ancestors $START # echo echo "=================" echo "= Descendents of process $START" echo "=================" lookup_descendents $START /bin/rm $FILE fi