本文在上一節《Linux v2.6內核編程之最簡單的內核模塊helloworld》的基礎上,添加了模塊參數,並拓展為多個源文件組成的內核模塊。
先直接上代碼:
主文件:
/* file name: sayhi.c * author: yilonglucky#gmail.com * description: a kernel module with parameters */ #include <linux/init.h> #include <linux/module.h> #include "farewell.h" static int times = 1; static char *whom = "world"; static int debug = 0; module_param(times, int, S_IRUGO); module_param(whom, charp, S_IRUSR); module_param(debug, int, S_IRUGO|S_IWUSR); static int hello_init(void) { int i; if(debug) { printk(KERN_ALERT "###times:%d\n", times); } for(i = 0; i < times; i++) { printk(KERN_ALERT "#%d: Hi, %s!\n", i, whom); } return 0; } static void hello_exit(void) { if(debug) { printk(KERN_ALERT "###whom:%s\n", whom); } farewell_to(whom); } module_init(hello_init); module_exit(hello_exit); MODULE_LICENSE("Dual BSD/GPL");
需要引用的用戶自定義頭文件:
/* file name: farewell.h * author: yilonglucky#gmail.com * description: a kernel module with parameters */ void farewell_to(char *);
引用的函數原型所在源文件:
/* file name: farewell.c * author: yilonglucky#gmail.com * description: a kernel module with parameters */ #include <linux/kernel.h> void farewell_to(char *s) { printk("Farewell, %s\n", s); return; }
最后是對應的Makefile:
ifneq ($(KERNELRELEASE),) obj-m:=greet.o greet-objs:=sayhi.o farewell.o else KERNELDIR ?= /lib/modules/$(shell uname -r)/build PWD := $(shell pwd) default: $(MAKE) -C $(KERNELDIR) M=$(PWD) modules clean: -rm -rf .* *.o *.ko *.mod.c *.order *.symvers endif
本例內核模塊的功能是在添加的模塊的時候,根據傳入的內核模塊參數,向內核log中向相應的名稱打招呼若干次,默認向world說一次Hi。
編譯出的內核模塊名字是greet.ko,源代碼在sayhi.c和farewell.c這2個源文件中,其中后者是被調用的角色,在更進一步的用法中,可以以so庫的形式鏈接進來。
在實際使用內核模塊時,為了便於調試可以添加控制調試信息的內核模塊參數。在本例中,默認關閉調試標志。
舉例操作序列:
#sudo insmod greet.ko whom=csdn times=5 debug=1
#dmesg
#ls -l /sys/modules/greet/parameters
#echo 0 > /sys/modules/greet/parameters/debug
#sudo rmmod greet
#dmesg
說明:
在源代碼中,在定義內核模塊參數的時候指定了相應的權限,這在成功加載模塊后可以看到。
關於宏S_IRUGO和S_IWUSR,定義在linux/stat.h中,實際上是文件訪問權限的八進制掩碼,轉貼部分代碼如下:
#define S_IRWXU 00700 #define S_IRUSR 00400 #define S_IWUSR 00200 #define S_IXUSR 00100 #define S_IRWXG 00070 #define S_IRGRP 00040 #define S_IWGRP 00020 #define S_IXGRP 00010 #define S_IRWXO 00007 #define S_IROTH 00004 #define S_IWOTH 00002 #define S_IXOTH 00001 #endif #ifdef __KERNEL__ #define S_IRWXUGO (S_IRWXU|S_IRWXG|S_IRWXO) #define S_IALLUGO (S_ISUID|S_ISGID|S_ISVTX|S_IRWXUGO) #define S_IRUGO (S_IRUSR|S_IRGRP|S_IROTH) #define S_IWUGO (S_IWUSR|S_IWGRP|S_IWOTH) #define S_IXUGO (S_IXUSR|S_IXGRP|S_IXOTH)
本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。