1. hello.c
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h> MODULE_AUTHOR("Tang*");
MODULE_DESCRIPTION("My First Try to Kernel Module");
MODULE_LICENSE("GPL"); static int hello_init(void)
{
printk(KERN_ALERT "Hello World Enter\n");
return ;
} module_init(hello_init); static void hello_exit(void)
{
printk(KERN_ALERT "Hello World Exit\n");
} module_exit(hello_exit);
2. Makefile
obj-m += hello.o CURRENT_PATH:=$(shell pwd)
LINUX_KERNEL:=$(shell uname -r)
LINUX_KERNEL_PATH:=/usr/src/kernels/$(LINUX_KERNEL) all:
make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) modules
clean:
make -C $(LINUX_KERNEL_PATH) M=$(CURRENT_PATH) clean
3. make //编译,生成hello.ko
4. insmod hello.ko //加载hello模块,会打印“Hello World Enter”
lsmod | grep hello //lsmod打印所有的内核模块,有显示"hello",表明hello模块已被加载
rmmod hello.ko //卸载hello模块,会打印"Hello World Exit"
lsmod | grep hello //不显示"hello",表明hello模块已被卸载
注:
对于CentOS系统,/usr/src/kernels/xxx(内核版本)/ 目录为空,导致编译内核模块失败。
解决方法:安装kernel-devel组件 或 安装整个内核源代码
参考:http://wiki.centos.org/zh/HowTos/I_need_the_Kernel_Source
参考:http://wiki.centos.org/zh/HowTos/I_need_the_Kernel_Source
我的做法:安装kernel-devel
1.uname -r获得内核版本号,我的是2.6.32-358.el6.x86_64;
2.到http://rpmfind.net/linux/rpm2html/search.php?query=kernel-devel下载与内核版本号对应的kernel-devel,我的是kernel-devel-2.6.32-358.el6.x86_64.rpm;
3.安装kernel-devel,rpm -ivh kernel-devel-2.6.32-358.el6.x86_64.rpm;
2.到http://rpmfind.net/linux/rpm2html/search.php?query=kernel-devel下载与内核版本号对应的kernel-devel,我的是kernel-devel-2.6.32-358.el6.x86_64.rpm;
3.安装kernel-devel,rpm -ivh kernel-devel-2.6.32-358.el6.x86_64.rpm;
4.ls /usr/src/kernels/2.6.32-358.el6.x86_64,此目录下不再为空。