1. hello.c
1 #include <linux/module.h>
2 #include <linux/kernel.h>
3 #include <linux/init.h>
4
5 MODULE_AUTHOR("TangHuimin");
6 MODULE_DESCRIPTION("My First Try to Kernel Module");
7 MODULE_LICENSE("GPL");
8
9 static int hello_init(void)
10 {
11 printk(KERN_ALERT "Hello World Enter
");
12 return 0;
13 }
14
15 module_init(hello_init);
16
17 static void hello_exit(void)
18 {
19 printk(KERN_ALERT "Hello World Exit
");
20 }
21
22 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
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,此目录下不再为空。