Chinaunix首页 | 论坛 | 博客
  • 博客访问: 174683
  • 博文数量: 30
  • 博客积分: 2010
  • 博客等级: 大尉
  • 技术积分: 440
  • 用 户 组: 普通用户
  • 注册时间: 2008-07-23 19:45
文章分类

全部博文(30)

文章存档

2016年(2)

2010年(3)

2009年(8)

2008年(17)

我的朋友

分类: LINUX

2008-10-12 20:33:29

#include<linux/init.h>
#include<linux/module.h>
#include<linux/sched.h>
#include<linux/sem.h>
#include<linux/list.h>

MODULE_LICENSE("Dual BSD/GPL");
static int hello_init(void)
{
      struct task_struct *task,*p;
      struct list_head *pos;
      int count=0;
      printk(KERN_ALERT"Hello World enter begin:\n");
      task=&init_task;
      list_for_each(pos,&task->tasks)
               {
               p=list_entry(pos, struct task_struct, tasks);
               count++;
               printk(KERN_ALERT"%d--->%s\n",p->pid,p->comm);
               }
      printk(KERN_ALERT"the number of process is:%d\n",count);
      return 0;
}
static void hello_exit(void)
{
  printk(KERN_ALERT"hello world exit\n");
}
module_init(hello_init);
module_exit(hello_exit);
/*Makefile文件:
obj-m :=process.o
CURRENT_PATH := $(shell pwd)
LINUX_KERNEL := $(shell uname -r)
LINUX_KERNEL_PATH := /usr/src/linux-headers-$(LINUX_KERNEL)

all:
       make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules
clean:
       rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions Module.symvers .Makefile.swp
*/

前面介绍了内核中的struct list_head结构,list_head结构只是为了服务于其他内核的结构而设计,那
么其他结构如何利用它呢?我在这里用struct task_struct 结构来说明。此结构定义如下(有所省略):
struct task_struct {
        volatile long state;    /* -1 unrunnable, 0 runnable, >0 stopped */
        void *stack;
        atomic_t usage;
        unsigned int flags;     /* per process flags, defined below */
        unsigned int ptrace;
    .......
        struct list_head tasks;
    .......
      pid_t pid;
        pid_t tgid;
        .....
        char comm[TASK_COMM_LEN];
    .....
};
其中就有list_head型的tasks域,他将内核中所有的进程都连接在一起。这个时候我们就可以利用list_for_each()函数来遍历整个进程项中的tasks。然后再用list_entry()函数找到task_struct的地址,这样就可以打印进程的pid和comm域了。如果不知道这两个宏的意思,可以再看看我前面的文章。
阅读(3489) | 评论(1) | 转发(0) |
0

上一篇:内核链表2

下一篇:进程的存在

给主人留下些什么吧!~~

chinaunix网友2008-10-13 15:20:03

虽然例子简单,但很能说明问题,不错。