Linux Kernel 學習筆記2:模組引數
阿新 • • 發佈:2019-01-02
(本章基於:linux-4.4.0-37)
在使用者態下程式設計可以通過main()來傳遞命令列引數,而編寫一個核心模組則可通過巨集module_param()來傳遞命令列引數.
先來看看這個巨集的定義(Linux-4.4.0-37)
#define module_param(name, type, perm) \
module_param_named(name, name, type, perm)
name:引數名
type:引數型別,byte, short, ushort, int, uint, long, ulong, charp, bool, invbool
perm:許可權S_IRUGO, S_IWUGO
例:hello.c
#include <linux/init.h> #include <linux/module.h> static int num = 0; static char *name = NULL; module_param(num, int, S_IRUGO); module_param(name, charp, S_IRUGO); static __init int hello_init(void) { printk(KERN_WARNING "helloworld init!\n"); printk(KERN_ALERT "num=%d\nname=%s\n", num, name); return 0; } static __exit void hello_exit(void) { printk(KERN_WARNING "helloworld exit!\n"); } module_init(hello_init); module_exit(hello_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Stone");
可在載入模組時帶入引數初始值:
#insmod helloworld.ko name=aaaa num=43
檢視核心引數
可在/sys/module/helloworld/parameters/中看到各引數對應的檔案,cat其內容可看到引數具體值。
備註:書上說若引數具有許可權S_IWUGO即可修改引數值,但試驗後發現加上S_IWUGO後無法通過編譯,錯誤如下,望大神指點:
include/linux/bug.h:33:45: error: negative width in bit-field ‘<anonymous>’ #define BUILD_BUG_ON_ZERO(e) (sizeof(struct { int:-!!(e); })) ^ include/linux/kernel.h:831:3: note: in expansion of macro ‘BUILD_BUG_ON_ZERO’ BUILD_BUG_ON_ZERO((perms) & 2) + \ ^ include/linux/moduleparam.h:225:6: note: in expansion of macro ‘VERIFY_OCTAL_PERMISSIONS’ VERIFY_OCTAL_PERMISSIONS(perm), level, flags, { arg } } ^ include/linux/moduleparam.h:167:2: note: in expansion of macro ‘__module_param_call’ __module_param_call(MODULE_PARAM_PREFIX, name, ops, arg, perm, -1, 0) ^ include/linux/moduleparam.h:147:2: note: in expansion of macro ‘module_param_cb’ module_param_cb(name, ¶m_ops_##type, &value, perm); \ ^ include/linux/moduleparam.h:126:2: note: in expansion of macro ‘module_param_named’ module_param_named(name, name, type, perm) ^ /root/modules/helloworld/hello.c:10:1: note: in expansion of macro ‘module_param’ module_param(name, charp, S_IWUGO); ^ scripts/Makefile.build:258: recipe for target '/root/modules/helloworld/hello.o' failed