Chinaunix首页 | 论坛 | 博客
  • 博客访问: 371828
  • 博文数量: 47
  • 博客积分: 967
  • 博客等级: 准尉
  • 技术积分: 1290
  • 用 户 组: 普通用户
  • 注册时间: 2012-05-25 16:14
文章分类

全部博文(47)

文章存档

2019年(1)

2014年(1)

2013年(9)

2012年(36)

分类: LINUX

2012-07-31 18:51:04


  1. #include <linux/kernel.h>
  2. #include <linux/module.h>
  3. #include <linux/init.h>
  4. #include <linux/sched.h>
  5. #include <linux/list.h>

  6. static __init int print_pid(void)
  7. {
  8.     struct task_struct *task,*p;
  9.     struct list_head *pos;
  10.     int count=0;
  11.     printk("Hello,let begin\n");
  12.     task=&init_task;
  13.     list_for_each(pos,&task->tasks)
  14.     {
  15.         p=list_entry(pos,struct task_struct,tasks);
  16.         count++;
  17.         printk("%d---->%s\n",p->pid,p->comm);
  18.     }
  19.     printk("the number of process is:%d\n",count);
  20.     return 0;
  21. }
  22. static __exit void print_exit(void)
  23. {
  24.     printk("<0>end!\n");
  25. }
  26. module_init(print_pid);
  27. module_exit(print_exit);
我们写一个Makefile文件来编译模块,内容如下:
  1. obj-m:=print_pid.o //文件名
  2. kernel_path=/usr/src/linux-headers-$(shell uname -r)

  3. all:
  4. make -c $(kernel_path)
  5. clean:
  6. make -c $(kernel_path) M=$(PWD)
最后,用make命令运行Makefile.
  1. lwp@lwp-linux:~/kernel$ make
运行代码用:
  1. lwp@lwp-linux:~/kernel$ sudo insmod print_pid.ko
从内核中移除该模块就可以看到退出时的信息:
  1. lwp@lwp-linux:~/kernel$ sudo rmmod print_pid
查看模块是否正确写入到内核中去:
  1. lwp@lwp-linux:~/kernel$ dmesg

阅读(4277) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~