首先在終端vim一個檔案名稱為hello.c,輸入內容如下:
1 #include <linux/module.h>
2 #include <linux/init.h>
3
4 MODULE_LICENSE("GPL");
5 MODULE_AUTHOR("Snooy");
6
7 static int howmany = 10;
8 module_param(howmany,int,S_IRUGO);
9
10 static char *name = "Snooy";
11 module_param(name,charp,S_IRUGO);
12
13 static __init int hello_init(void) //只被用一次就丟棄__init
14 {
15 int i = 0;
16 for(; i<howmany; i++)
17 printk(KERN_EMERG"this is %s!\n",name);
18 return 0;
19 }
20
21 static __exit void hello_exit(void)
22 {
23 printk("<0>goodbye!\n");
24 }
25
26 module_init(hello_init); //module_...是一個宏
27 module_exit(hello_exit);
28 //另一種寫法如下:
29 //若不要18/19行,則7,13行可改為函數的如下:
30 //int init_module(void) 函數調運
31 //void exit_module(void) 函數調運
編寫編譯需要的Makefile(注意這裡好像必須大寫M,否則報錯),內容如下:
1 ifeq ($(KERNELRELEASE),)
2 KERNELDIR ?= /usr/src/kernels/2.6.18-164.el5-i686/ #這裡的路徑依據自己虛擬機器linux版本決定(查看指令:uname -r)
3 PWD := $(shell pwd) #這裡擷取帶擴充的路徑
4 modules:
5 $(MAKE) -C $(KERNELDIR) M=$(PWD) modules
6
7 .PHONY: clean
8 clean:
9 rm -rf *.ko *.o Module* *.mod*
10 else
11 obj-m := hello.o
12 endif
解釋:該Makefile在執行make時會進入兩次,具體自己根據if等理解。
使用指令:
insmod hello.ko 安裝模組
lsmod 查看已安裝模組
rmmod hello 或 rmmod hello.ko 刪除模組
dmesg 查看模組運行資訊(最後幾行),或者查看cat /var/log/messages資訊也行。
到此一個簡單的入門驅動模組編寫安裝與體驗結束。