linux内核模块遍历获取进程列表,使用list_entry()

使用方法:

编写Makefile如下:

obj-m +=pscmd.o
all:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
        make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

 

然后执行如下命令

insmod pscmd

cat /proc/pscmd

然后就会显示出进程列表

 

 struct task_struct {
    
//xxxxxxx
    struct hlist_head preempt_notifiers;
    
struct list_head rcu_node_entry;
    
struct list_head tasks;
    
struct list_head children;    /* list of my children */
    
struct list_head sibling;    /* linkage in my parent's children list */
    
struct list_head ptraced;
    
struct list_head ptrace_entry;
    
struct list_head thread_group;
    
//还有好多list,不抄了……
}

linux的task_struct(进程PCB)组织如上(只列出list_head部分),可以看到struct list_head tasks; 正是用这个结构将所有进程的PCB链接成了一个链表,结构定义如下:

struct list_head {
    
struct list_head *next, *prev;
};

图示如下:

linux内核模块遍历获取进程列表,使用list_entry()_第1张图片

所以遍历进程列表需要先找到一个进程的PCB首指针p,然后由p->tasks来遍历链表,遍历的时候使用宏list_entry来获取PCB首指针

list_entry(ptr,type,member)宏,

你可能感兴趣的:(LINUX基础)