文档介绍:Pstree源码分析
一.getopt_long获取参数,根据参数设置相应的变量。
二.read_proc ()主要函数,获取所有的process,生成tree.
#define PROC_BASE "/proc"
dir =为command
while ((dt = readdir(taskdir)) != NULL)
if ((thread=atoi(dt->d_name)) !=0)
//读取/proc/number/task中的number
if (thread != pid)
//即该number!=pid,也就是该process有子线程
add_proc(threadname, thread, pid, , NULL, 0);
………………..
…………………略
add_proc (comm, pid, ppid, , NULL, 0);
add_proc()函数
add_proc (const char *comm, pid_t pid, pid_t ppid, uid_t uid,
const char *args, int size)
if (!(this = find_proc (pid)))
this = new_proc (comm, pid, uid); //如果没有该process,则生成该pid对应的PROC结构
else
{
strcpy (this->comm, comm);
this->uid = uid;
}
if (!(parent = find_proc (ppid)))
parent = new_proc ("?", ppid, 0);
//如果没有该ppid对应的process,则生成ppid对应的PROC结构
…………………略
add_child (parent, this);
add_child()函数
add_child (PROC * parent, PROC * child)
CHILD *new, **walk;
new = malloc (sizeof (CHILD))
new->child = child;
for (walk = &parent->children; *walk; walk = &(*walk)->next)
//在该parent对应的children链中循环
if ((cmp = strcmp ((*walk)->child->comm, child->comm)) > 0)
break;
else if (!cmp && (*walk)->child->uid > child->uid)
break;
new->next = *walk;
*walk = new;
//在children链中找到合适的位置将该child添加进去
添加规则:
,按children的uid从小到大排序
三.dump_tree主要函数,将tree按规则输出
dump