在用户态下编程可以通过main()的来传递命令行参数,而编写一个内核模块则通过module_param ()
module_param宏是Linux 2.6内核中新增的,该宏被定义在include/linux/moduleparam.h文件中,具体定义如下:
#define module_param(name, type, perm)
module_param_named(name, name, type, perm)
其中使用了 3 个参数:要传递的参数变量名, 变量的数据类型, 以及访问参数的权限。
static char *whom = "world";
static int howmany = 1;
module_param (howmany, int, S_IRUGO);
module_param (whom, charp, S_IRUGO);
模块参数支持许多类型:
#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
使用 S_IRUGO 作为参数可以被所有人读取, 但是不能改变; S_IRUGO|S_IWUSR 允许 root 来改变参数. 注意, 如果一个参数被 sysfs 修改, 你的模块看到的参数值也改变了, 但是你的模块没有任何其他的通知. 你应当不要使模块参数可写, 除非你准备好检测这个改变并且因而作出反应.
通过宏MODULE_PARM_DESC()对参数进行说明:
static unsigned short size = 1;
module_param(size, ushort, 0644);
MODULE_PARM_DESC(size, “The size in inches of the fishing pole connected to this computer.” );
module_param() 和module_param_array() 的作用就是让那些全局变量对insmod 可见,使模块装载时可重新赋值。
module_param_array() 宏的第三个参数用来记录用户insmod 时提供的给这个数组的元素个数,NULL 表示不关心用户提供的个数
module_param() 和module_param_array() 最后一个参数权限值不能包含让普通用户也有写权限,否则编译报错。这点可参考linux/moduleparam.h 中__module_param_call() 宏的定义。
字符串数组中的字符串似乎不能包含逗号,否则一个字符串会被解析成两个
一个测试用例:parm_hello.c
#include
#include
#include
#defineMAX_ARRAY 6
staticintint_var=0;
staticconstchar*str_var="default";
static int int_array[6];
intnarr;
module_param(int_var,int,0644);
MODULE_PARM_DESC(int_var,"A integer variable");
module_param(str_var,charp,0644);
MODULE_PARM_DESC(str_var,"A string variable");
module_param_array(int_array,int,&narr,0644);
MODULE_PARM_DESC(int_array,"A integer array");
staticint__init hello_init(void)
{
inti;
printk(KERN_ALERT"Hello, world.\n");
printk(KERN_ALERT"int_var %d.\n",int_var);
printk(KERN_ALERT"str_var %s.\n",str_var);
for(i=0;i
测试:insmod parm_hello.ko int_var=100 str_var=hello int_array=100,200