#!/bin/sh
#Copyright 2003 William Stearns <wstearns@pobox.com>

#Requires: awk, grep, ls, pgrep, tty

while [ -n "$1" ]; do
	case $1 in
	-v)
		Verbose='yes'
		;;
	*)
		echo Unrecognized option "$1"
		;;
	esac
	shift
done

TTY="`tty`"
ShortTTY=${TTY##/dev/}

Family=$(pgrep -t $ShortTTY) #Everything on the current terminal, includes $$ and $PPID

Family=" $(echo $Family) "

#OK, now keep adding the parents of all of these tasks until the list goes all the way back to init - pid 1.
while ! echo "$Family" | grep -q ' 1 ' ; do
	for OneChild in $Family ; do
		Dad=$(grep '^PPid:' /proc/$OneChild/status | awk '{print $2}')
		if ! echo "$Family" | grep -q " $Dad " ; then
			Family="$Family$Dad "
		fi
	done
done

#Now, we exclude kernel threads
cd /proc

#If we're root, list off the kernel threads so we don't stop those.
#If we're not root, we can't stop them anyways, so don't worry about it (good, 
#because ls -al */exe fails - doesn't return apps - as non-root).
if [ "$EUID" -eq 0 ]; then
	for OneThread in `ls -al */exe 2>/dev/null | grep -v ' -> ' | awk '{print $9}'` ; do
		KThreads="$KThreads ${OneThread%%/exe*}"
	done
fi

if [ -n "$Verbose" ]; then
	echo My PID is $$, I\'m on terminal $ShortTTY
	echo I\'ll exclude the following PIDs:
	echo Family: $Family
	echo Kernel Threads: $KThreads
fi

#ps axf | grep -A 5 -B 5 freeze

cd /proc
for OnePID in [0-9]* ; do
	Skip=0
	for OneExclude in $Family $KThreads ; do
		if [ $OnePID -eq $OneExclude ]; then
			Skip=1
			break 1	#No need to test against any other PIDs, we found a match
		fi
	done
	if [ $Skip -eq 0 ]; then
		KilledPIDs="$KilledPIDs $OnePID"
		################kill -STOP $OnePID || echo failed to send STOP to $OnePID
	else
		SkippedPIDs="$SkippedPIDs $OnePID"
	fi
done

if [ -n "$Verbose" ]; then
	echo These PIDs were sent a STOP:
	echo $KilledPIDs
	echo These PIDs were skipped:
	echo $SkippedPIDs
fi


exit 0
#Garbage

Family () {
#Single command line parameter is tty
	Family=" $(lsof -t $1) "
	Family2=" $(lsof -t $1) "
	for OnePID in $Family $Family2 ; do
		if echo "$Family" | grep -q " $OnePID " ; then
			if echo "$Family2" | grep -q " $OnePID " ; then
				if ! echo "$FinalList" | grep -q " $OnePID " ; then
					echo adding $OnePID >&2
					FinalList = "$FinalList$OnePID "
				fi
			fi
		fi
	done
	#FDDir="`ls -al /proc/$1/fd/{0,1,2}`"

	#FamDups=$(lsof -t $1 ; lsof -t $1)
	#echo "$FamDups" >&2
	#FamList=$(echo "$FamDups" | sort | uniq -d)

	pgrep -t pts/22

	echo $FamList
}