01.
#include <linux/kernel.h>
02.
#include <linux/module.h>
03.
#include <linux/init.h>
04.
#include <linux/sched.h>
05.
#include <linux/list.h>
06.
07.
static
__init
int
print_pid(
void
)
08.
{
09.
struct
task_struct *task,*p;
10.
struct
list_head *pos;
11.
int
count=0;
12.
printk(
"Hello,let begin\n"
);
13.
task=&init_task;
14.
list_for_each(pos,&task->tasks)
15.
{
16.
p=list_entry(pos,
struct
task_struct,tasks);
17.
count++;
18.
printk(
"%d---->%s\n"
,p->pid,p->comm);
19.
}
20.
printk(
"the number of process is:%d\n"
,count);
21.
return
0;
22.
}
23.
24.
static
__exit
void
print_exit(
void
)
25.
{
26.
printk(
"<0>end!\n"
);
27.
}
28.
module_init(print_pid);
29.
module_exit(print_exit);
我们写一个Makefile文件来编译模块,内容如下:
www.it165.net
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.
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