#!/bin/sh
#
# Copyright (c) 2008 by Bruce Blinn
#
# NAME
#	ppid - print the process ID of the parent process
#
# SYNOPSIS
#	ppid [-rv] processID
#
# DESCRIPTION
#	Print the process ID of the parent process of the specified
#	process.
#
# OPTIONS
#	-r	Recursive.  If the -r option is used, all parent
#		processes up to the top of the process tree (that
#		is, the init process) will be printed.
#
#	-v	Verbose.  Print the name of the process in addition
#		to the process ID.
#
# RETURN VALUE
#	0	Successful completion.
#	1	Error - see the message written to standard error.
#
####################################################################
CMDNAME=$(basename $0)
USAGE="Usage: $CMDNAME [-rv] processID"
RECURSIVE=FALSE		# Recursive option.
VERBOSE=FALSE		# Verbose option.
VOPT=			# Verbose option for recursion.
PID=			# PID of the child (original process).
PARENT=			# PID of the parent being processed.
export UNIX95=		# For POSIX version of ps command on HP-UX.

while getopts rv OPT
do
	case $OPT in
		r)	RECURSIVE=TRUE
			;;
		v)	VERBOSE=TRUE
			VOPT="-v"
			;;
		\?)	echo "$USAGE" 1>&2
			exit 1
			;;
	esac
done
shift $((OPTIND - 1))

if [ $# -ne 1 ]; then
	echo "$USAGE" 1>&2
	exit 1
fi

PID=$1
PARENT=$(ps -p $PID -o ppid=)

if [ "$PARENT" -ne "0" ]; then
	if [ "$RECURSIVE" = "TRUE" ]; then
		$0 $VOPT -r $PARENT
	fi

	if [ "$VERBOSE" = "TRUE" ]; then
		echo "$PARENT	$(pname $PARENT)"
	else
		echo $PARENT
	fi
fi
