Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

find all child and parent processes of a PID

Shell Scripts

find all child and parent processes of a PID

by  gregor weertman  Posted    (Edited  )
This faq contains 1 script

Find all Parent and child processes of a pid.
example:
child [color red]26249[/color] --> finds

root 3634 26249 0 15:00:16 ttyq5 0:00 sleep 222
root [color red]26249[/color] 26248 0 Jan 8 ttyq5 0:01 /usr/bin/ks
root 26248 1208 0 Jan 8 ttyq5 0:00 telnetd -b
root 1208 1 0 Nov 21 ? 12:55 /usr/sbin/i
root 1 0 0 Nov 21 ? 1:01 init
root 0 0 0 Nov 21 ? 107:22 swapper


root 3625 26249 0 15:00:09 ttyq5 0:00 sleep 1111
root [color red]26249[/color] 26248 0 Jan 8 ttyq5 0:01 /usr/bin/ks
root 26248 1208 0 Jan 8 ttyq5 0:00 telnetd -b
root 1208 1 0 Nov 21 ? 12:55 /usr/sbin/i
root 1 0 0 Nov 21 ? 1:01 init
root 0 0 0 Nov 21 ? 107:22 swapper


child 1 --> You get all the trees

have fun!

#!/usr/bin/sh
# Find all the child and parent processes of a pid.
# By Gregor Weertman

pid=$1
if [ -z "$1" ] ;then
echo child pid ...
exit
fi

for pid
do
ps -ef |awk -vpd=$pid '
function child( fpid, ff){
ret = 1
for( ii[ ff] = 1; ii[ ff] <= TNR; ii[ ff]++){
if( ppid[ ii[ ff]] == fpid) {
a = pid[ ii[ ff]]
pd1 = pid[ ii[ ff]]
child( pd1, ff + 1)
}
}
if( a != b && length( a != 0)) {
print "\n"
parent( a, ff)
ret = 0
}
b=a
return ret
}
function parent( fpid, ff){
for( ii[ ff] = 1; ii[ ff] <= TNR; ii[ ff]++){
if( pid[ ii[ ff]] == fpid) {
print psln[ ii[ ff]]
pd1 = ppid[ ii[ ff]]
ppd1 = pid[ ii[ ff]]
if( pid[ ii[ ff]] == ppid[ ii[ ff]]) return 3
ret = parent( pd1, ff + 1)
return 2
}
if( ret == 3) return 1
}
return 0
}
{
pid[ NR] = $2
ppid[ NR] = $3
psln[ NR] = $0
if( pid[ NR] == pd) {
# print "BEGIN:" psln[ NR] "\n"
print "\n"
pd1 = pid[ NR]
}
TNR = NR
}
END{
if( pd1 == 0) exit
if( child( pd1, 1) == 1) parent( pd1, 1)
}'
done




Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top