- #include <linux/kernel.h>
- #include <linux/module.h>
- #include <linux/init.h>
- #include <linux/sched.h>
- #include <linux/list.h>
- static __init int print_pid(void)
- {
- struct task_struct *task,*p;
- struct list_head *pos;
- int count=0;
- printk("Hello,let begin\n");
- task=&init_task;
- list_for_each(pos,&task->tasks)
- {
- p=list_entry(pos,struct task_struct,tasks);
- count++;
- printk("%d---->%s\n",p->pid,p->comm);
- }
- printk("the number of process is:%d\n",count);
- return 0;
- }
- static __exit void print_exit(void)
- {
- printk("<0>end!\n");
- }
- module_init(print_pid);
- module_exit(print_exit);
我们写一个Makefile文件来编译模块,内容如下:
- obj-m:=print_pid.o //文件名
- kernel_path=/usr/src/linux-headers-$(shell uname -r)
- all:
- make -c $(kernel_path)
- clean:
- make -c $(kernel_path) M=$(PWD)
最后,用make命令运行Makefile.
- lwp@lwp-linux:~/kernel$ make
运行代码用:
- lwp@lwp-linux:~/kernel$ sudo insmod print_pid.ko
从内核中移除该模块就可以看到退出时的信息:
- lwp@lwp-linux:~/kernel$ sudo rmmod print_pid
查看模块是否正确写入到内核中去:
- lwp@lwp-linux:~/kernel$ dmesg
阅读(4339) | 评论(0) | 转发(0) |