开发者

how to iterate over PCB's to show information in a Linux Kernel Module?

I want to write a little Linux Kernel Module that can show me the PID of all running processes. I have the following code:

/*
 * procInfo.c  My Kernel Module for process info
 */

#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>

/*
 * The init function, called when the module is loaded.
 * Returns zero if successfully loaded, nonzero otherwise.
 */
static int mod_init(void)
{
        printk(KERN_ALERT "ProcInfo sucessfully loaded.\n");
        return 0;
}

/*
 * The exit function, called when the module is removed.
 */
static void mod_exit(void)
{
        printk(KERN_ALERT "ProcInfo sucessfully unloaded.\n");
}

void getProcInfo()
{
        printk(KERN_INFO "The process is \"%s\" (pid %i)\n",
        current->comm, current->pid);
}

module_init(mod_init);
module_exit(mod_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Rodrigo");

As you can see, i know i have to use the *struct task_struct* structure to get the PID and the Process name, but i am using current, and i know the existance of some double linked circular list that contains all PCB's, so the main question is: what do i need to ad开发者_StackOverflowd to iterate over this linked lisk with p-next_task and p-prev_task so getProcInfo works? Thanks!


The following macros from include/linux/sched.h may be useful:

#define next_task(p) \
    list_entry_rcu((p)->tasks.next, struct task_struct, tasks)

#define for_each_process(p) \
    for (p = &init_task ; (p = next_task(p)) != &init_task ; )

You probably need to hold the tasklist_lock before calling these macros; several examples of how to lock, iterate, and unlock, are in mm/oom_kill.c.


Actually, for newer kernels (2.6.18 and newer) the proper way to list tasks is by holding an rcu lock, because task list is now an RCU list. Also tasklist_lock is no more exported symbol - it means that when you are compiling a loadable kernel module, this symbol will not be visible for you.

example code to use

struct task_struct *task;
rcu_read_lock();                                                    
for_each_process(task) {                                             
      task_lock(task);                                             

      /* do something with your task :) */

      task_unlock(task);                                           
}                                                                    
rcu_read_unlock();                       

Also documentation about RCU in linux kernel source directory can be helpful and you will find it in Documentation/RCU

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜