1.简单的内核模块实例(hello.c)
# include<linux/kernel.h>注意:static int __init 其中int后面有一个空格,init前有两道下划线。详情参见。
# include<linux/module.h>
# include<linux/init.h>
static int __init hello_init(void)
{
printk(KERN_INFO "Hello world\n");
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_INFO "Goodbye world\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
2.编写Makefile文件[root@localhost star]# vi Makefile
obj-m := hello.o注意:
all:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(shell pwd) clean
- 在all和clean下面的命令行前面是按Tab形成的空当,切不可按成“空格键”。我就是输入错误导致make命令不成功。
- 其中-C后指定的是Linux内核源代码的目录,而M=后指定的是hello.c和Makefile所在的目录
make -C /lib/modules/2.6.18-371.el5/build M=/home/star modules
make[1]: Entering directory `/usr/src/kernels/2.6.18-371.el5-i686'
CC [M] /home/star/hello.o
Building modules, stage 2.
MODPOST
CC /home/star/hello.mod.o
LD [M] /home/star/hello.ko
make[1]: Leaving directory `/usr/src/kernels/2.6.18-371.el5-i686'
显示上面的情况表明编译成功。(2)查看编译生成的模块信息[root@localhost star]# modinfo hello.ko
filename: hello.ko
srcversion: 2BC3DDDE2F3989DA1A22677
depends:
vermagic: 2.6.18-371.el5 SMP mod_unload 686 REGPARM 4KSTACKS gcc-4.14.装载和卸载模块(必须root用户)(1)insmod(install module);rmmod(remove module)装载 insmod hello.ko卸载 rmmod hello.ko(2)查看已经装载的模块(命令lsmod显示所有装载模块) [root@localhost star]# lsmod | grep hellohello 5504 0该命令可以直接找到自己添加的模块
(3)运行模块dmesg( diagnostic message)输入命令 dmesg(或者用 cat /var/log/messages查看系统日志文件)一般在最后两行可以看见下面,表示执行了装载和卸载过程。Hello world
Goodbye world
相关链接:内核模块编程入门:http://www.tldp.org/LDP/lkmpg/2.6/html/index.html