1.创建一个目录#mkdir zhu
#cd zhu
#vim hello.c 编写一个名为hello的文件
2.hello.c:
#include <linux/module.h> //所有模块都需要的头文件
#include <linux/init.h>
static int hello_init(void)
{
printk(KERN_ERR "hello world");
return 0;
}
static void hello_exit(){
printk(KERN_EMERG "hello exit!");
}
module_init(hello_init);
module_exit(hello_exit)
3.#vim makefile 写makefile文件
Makefile:
-
- ifneq ($(KERNELRELEASE),)
- obj-m :=hello.o
- else
- KDIR :=/lib/modules/$(shell uname -r)/build
- all:
- make -C $(KDIR) M=$(PWD) modules
- clean:
- rm -f *.ko *.o *.mod.o *.mod.c *.symvers
- endif
注意: 书写Makefile文件时命令行前要按【Tab】键
4.#make 编译模块
5.出错1:“/root/zhu/Makefile: no such file or directory ” 是因为makefile 未大写成Makefile
## mv makefile Makefile
出错2:“syntax error near unexpected token '/build' ” 是因为附近有语法错误,最后知道是一个符号写错。
6.重新修改代码后make 成功。生成hello.ko
7.#insmod hello.ko 加载模块
#lsmod | grep hello
hello 12496 0
8.模块的代码是在内核中运行的,所以必须要看内核缓冲区控制信息。
#dmesg 来查看具体模块代码运行情况