[source] ptree (sh/awk)

bridged with qdn.public.qnxrtp.applications
Post Reply
Guest

[source] ptree (sh/awk)

Post by Guest » Sat Oct 26, 2002 7:23 pm

Something like /usr/proc/bin/ptree [pid] in SunOS.
Similar thing available in psin, but requires Photon.

Of course if you want more functions for this
(like dumping "pidin mem" along?) you should whip up a C program
but just getting the tree was possible with single pidin and awk.
--
kabe

#!/bin/sh
#if __USAGE
#%C - print the process tree
#
#Usage:
# ptree [pid]
#endif

STARTPID=1
if [ $# -gt 0 ]; then STARTPID=$1; shift; fi
# using "pidin -f A" screws a lot if any command's argument had "\n"
pidin -F '%e %a %n' | awk -v startpid=$STARTPID '
# ppid pid args
{
if ($1 == "1" && $2 == "procnto") {
ppid=1; pid=1; args=" procnto";
largs[pid]=args;
} else {
ppid=$1; pid=$2;
$1=""; $2=""; args=$0;
#sub("\n"," ");
if ( ! largs[pid]) {
# stash info:
# largs[pid] command name
# lchild[pid,0..childs[pid]-1] pids of children
# parentof[pid]
largs[pid]=args;
t=childs[ppid]+0; lchild[ppid,t]=pid; childs[ppid]++;
parentof[pid]=ppid;
}
}
}

function ptree(pid,sprefix, i) {
printf("%s%d%s\n", sprefix,pid,largs[pid]);
if (childs[pid]) {
for (i=0; i < childs[pid]; i++) {
ptree(lchild[pid,i], sprefix " ", depth+1);
}
}
}
END {
pid = startpid;
if (pid != 1 && ! parentof[pid]) {
print pid ": no process"
exit
}
# backtrack up
blen = 0;
while (pid != 1) {
blist[blen++]=pid;
pid = parentof[pid];
}
# blist[0..blen-1] = startpid,p(startpid),...1
# descend from 1 until startpid
sprefix="";
while (pid != startpid) {
printf("%s%d%s\n", sprefix,pid,largs[pid]);
pid = blist[--blen];
sprefix=sprefix " ";
}
# full tree below
ptree(pid, sprefix);
}
'

Post Reply

Return to “qdn.public.qnxrtp.applications”