您的位置:首页 > 运维架构 > Linux

linux Kernel module简单模拟ps指令输出

2016-01-19 16:00 645 查看
一、方法

/* sched.h */
Struct task_struct {
…
list_head children;
list_head sibling;
…
};

1)
/* traver every process */
struct task_struct *task;
for_each_process( task )
{
/* handle the process info */
}

2)
/* traver the children of the init process */
struct task struct *task;
struct list head *list;
list for each(list,&init_task.children) {
task = list entry(list, struct task struct, sibling);
/* task points to the next child in the list */
}


二、实现

1) 简单遍历所有进程,直接使用for_each_process()即可;

do_ps( void )
{
struct task_struct *task;

printk( KERN_INFO "%-5s %-9s %s\n", "PID","STATE", "CMD" );
for_each_process( task )
{
printk( KERN_INFO "%-5d %-9c %s\n", task->pid,get_status_text( task->state ), task->comm );
}

return 0;
}


2) 采用深度优先的方式遍历,借助数据结构——栈;

(1) 将初始进程压栈;

(2) 如果栈不为空,进程出栈;若为空跳到(4);

(3) 将出栈进程的子进程压栈,返回(2);

(4) 结束进程遍历;

do_ps_dfs( void)
{
struct task_struct *task;
struct list_head   *list;
struct process_node *pCur;

printk( KERN_INFO"\n\n\n\n\n\n\n" );
printk( KERN_INFO "%-5s %-9s%s\n", "PID", "STATE", "CMD" );
push_process( &init_task );
while( ( pCur = pop_process() ) )
{
printk( KERN_INFO "%-5d %-9c%s\n", pCur->process->pid, get_status_text(pCur->process->state ), pCur->process->comm );
list_for_each( list, &( pCur->process->children) )
{
task = list_entry( list, structtask_struct, sibling );
push_process( task );
}
kfree( pCur );
}
return 0;
}


三、示例代码

http://download.csdn.net/detail/qq123386926/9410413
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: