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

本文介绍了如何在Linux内核模块中实现类似ps指令的功能,通过遍历进程并使用深度优先搜索策略,详细讲解了代码实现过程,并提供了示例代码链接。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、方法

/* 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.youkuaiyun.com/detail/qq123386926/9410413

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值