$ vi hello.c #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("Allen"); MODULE_DESCRIPTION("A Simple Hello World module"); static int __init hello_init(void) { printk(KERN_INFO "Enter module. Hello world!\n"); return 0; } static void __exit hello_exit(void) { printk(KERN_INFO "Exit module.\n"); } module_init(hello_init); module_exit(hello_exit);
$ vi Makefile obj-m += hello.o all: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules clean: make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean2. 編譯Hello world的kernel module
$ make make -C /lib/modules/3.11.0-15-generic/build M=/home/allen/Work/module modules make[1]: Entering directory `/usr/src/linux-headers-3.11.0-15-generic' CC [M] /home/allen/Work/module/hello.o Building modules, stage 2. MODPOST 1 modules CC /home/allen/Work/module/hello.mod.o LD [M] /home/allen/Work/module/hello.ko make[1]: Leaving directory `/usr/src/linux-headers-3.11.0-15-generic' $ ls hello.c hello.mod.c hello.o modules.order hello.ko hello.mod.o Makefile Module.symvers3. 掛載Hello world的kernel module
$ sudo insmod hello.ko $ dmesg | tail -1 [18253.619885] Enter module. Hello world!4. 卸載Hello world的kernel module
$ sudo rmmod hello $ dmesg | tail -1 [18291.787154] Exit module.5. 列出已掛載kernel module
$ lsmod | grep hello hello 12425 06. 顯示module的資訊
$ modinfo hello.ko filename: hello.ko description: A Simple Hello World module author: Allen license: GPL srcversion: 4022E1AB22D5C59AACC7122 depends: vermagic: 3.11.0-15-generic SMP mod_unload modversions7. 參考來源
How to Write Your Own Linux Kernel Module with a Simple Example
沒有留言:
張貼留言