2011-04-06 45 views
3

我想寫一點Linux內核模塊,可以顯示所有正在運行的進程的PID。 我有以下代碼:如何迭代PCB以在Linux內核模塊中顯示信息?

/* 
* 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"); 

正如你所看到的,我知道我必須使用*結構的task_struct *結構得到PID和進程名稱,但我使用當前,和我知道包含所有PCB的一些雙鏈接循環鏈表是否存在等,所以主要問題是: 什麼我需要添加到迭代與對next_task和p-prev_task所以getProcInfo的工作原理是聯lisk? 謝謝!

回答

5

include/linux/sched.h以下宏可能是有用的:

#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 ;) 

你可能需要調用這些宏之前舉行tasklist_lock;如何鎖定,迭代和解鎖的幾個例子在mm/oom_kill.c

+0

不是一個直接的答案,但它讓我找出答案!非常感謝! – RodrigoCR 2011-04-09 04:16:06

4

實際上,對於新的內核(2.6.18及更高版本)列出任務的正確方法是持有RCU鎖,因爲任務列表現在是一個RCU列表。另外tasklist_lock不再是導出的符號 - 這意味着當您編譯可加載的內核模塊時,此符號對您而言將不可見。

示例代碼使用

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();      

而且文檔有關RCU在Linux內核源代碼目錄可以是有益的,你會發現它在Documentation/RCU