文件hello.c(放在目录/root/lnq/modules/hello下):
#include<linux/kernel.h>
#include<linux/module.h>
#include<linux/init.h>
MODULE_LICENSE("GPL");
static int hello_init(void){ #模块初始化函数
printk(KERN_INFO "Hello,world!\n");
return 0;
}
static void hello_exit(){ #模块退出和清理函数
printk(KERN_INFO "Hello,exit!\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_AUTHOR("lnq");
MODULE_DESCRIPTION("This is hello modules");
MODULE_ALIAS("a simple example");
文件Makefile:
obj-m += hello.o #产生hello模块的目标文件
kernel_path=/usr/src/kernels/objms-kernel #自己的内核文件路径
all:
make -C $(kernel_path) M=$(pwd) modules #pwd是当前所在目录
clean:
make -C $(kernel_path) M=$(pwd) clean
编译:
make
编译成功之后,在此目录下会生成如下几个文件:
hello.c 、hello.ko 、 hello.mod.c 、 hello.mod.o 、 hello.o 、Makefile 、modules.order 、 Module.symvers
其中,hello.ko就是所需要的模块。
加载模块(会调用hello_init函数):
insmod hello.ko
如果加载成功,用dmesg查看可以看到打印出“hello,world!”信息。
查看模块:
lsmod
卸载模块(会调用hello_exit函数):
rmmod hello
如果卸载成功,用dmesg查看可以看到打印出“hello,exit!”信息。