Linux module練習手札I紀錄如何撰寫一個簡單的module,並且編輯它,以及load和unload一個module。
write a module
#include <linux/init.h> #include <linux/module.h> MODULE_LICENSE("GPL"); static int __init init_modules(void) { printk("hello world\n"); return 0; } static void __exit exit_modules(void) { printk("goodbye\n"); } module_init(init_modules); module_exit(exit_modules);<linux/init.h>和#include <linux/module.h>是Linux 任何的module都會用到的header file,init.h主要定義module的init和cleanup,如module_init()和module_exit()。而module.h定義了module所需要的資料結構與macro。
對於__init的解釋在init.h有非常好的解釋:
The kernel can take this as hint that the function is used only during the initialization phase and free up used memory resources after.
簡單的說就是這個function在初始化後(執行完)就被free了。
而__exit的解釋是:
__exit is used to declare a function which is only required on exit: the function will be dropped if this file is not compiled as a module.
module_init()的解釋是:
The module_init() macro defines which function is to be called at module insertion time (if the file is compiled as a module), or at boot time: if the file is not compiled as a module the module_init() macro becomes equivalent to __initcall(), which through linker magic ensures that the function is called on boot.
主要是用來設定當insert該module後,應該要被執行的進入點(enrty point)。
module_exit()的解釋是:
This macro defines the function to be called at module removal time (or never, in the case of the file compiled into the kernel). It will only be called if the module usage count has reached zero. This function can also sleep, but cannot fail: everything must be cleaned up by the time it returns.
Note that this macro is optional: if it is not present, your module will not be removable (except for 'rmmod -f').
簡言之,就是當user執行rmmod時,會被執行到的function。沒有module_exit(),module就不能被rmmod。
write a Makefile to manage the module
mname := brook_modules $(mname)-objs := main.o obj-m := $(mname).o KERNELDIR := /lib/modules/`uname -r`/build all: $(MAKE) -C $(KERNELDIR) M=`pwd` modules clean: $(MAKE) -C $(KERNELDIR) M=`pwd` clean$(mname)-objs是告訴make這個module有哪些object files。
obj-m是告訴make這個module的name是什麼。
KERNELDIR是告訴make這個module的kernel所在的位置。
後面就接兩個target(all/clean),用於處理產生和清除module用。