(本章基于: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