1. hello.cphp
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\n"); 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\n"); 20 } 21
22 module_exit(hello_exit);
2. Makefilehtml
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.kolinux
4. insmod hello.ko //加載hello模塊,會打印「Hello World Enter」shell
lsmod | grep hello //lsmod打印全部的內核模塊,有顯示"hello",代表hello模塊已被加載centos
rmmod hello.ko //卸載hello模塊,會打印"Hello World Exit"app
lsmod | grep hello //不顯示"hello",代表hello模塊已被卸載ui
注:spa
對於CentOS系統,/usr/src/kernels/xxx(內核版本)/ 目錄爲空,致使編譯內核模塊失敗。.net