linux模块参数分析

来源:互联网 发布:淘宝网双11销售额 编辑:程序博客网 时间:2024/05/22 06:05
module_param()理解
-------------------------------------------
在用户态下编程可以通过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 个参数:要传递的参数变量名, 变量的数据类型, 以及访问参数的权限。



perm参数的作用是什么?
-------------------------------------------
perm参数是一个权限值,表示此参数在sysfs文件系统中所对应的文件节点的属性。你应当使用 <linux/stat.h> 中定义的值. 这个值控制谁可以存取这些模块参数在sysfs中的表示.当perm为0时,表示此参数不存在sysfs文件系统下对应的文件节点。 否则, 模块被加载后,在/sys/module/目录下将出现以此模块名命名的目录, 带有给定的权限.。
权限在include/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

使用S_IRUGO作为参数可以被所有人读取, 但是不能改变; S_IRUGO|S_IWUSR允许root来改变参数. 注意, 如果一个参数被sysfs修改, 你的模块看到的参数值也改变了, 但是你的模块没有任何其他的通知. 你应当不要使模块参数可写, 除非你准备好检测这个改变并且因而作出反应.


module_param()应当放在任何函数之外, 典型地是出现在源文件的前面.定义如:
static char *whom = "world";
static int howmany = 1;
module_param(howmany, int, S_IRUGO);
module_param(whom, charp, S_IRUGO);

模块参数支持许多类型:
bool     一个布尔型(true或者false)值(相关的变量应当是int类型).
invbool invbool类型颠倒了值, 所以真值变成 false, 反之亦然.
charp    一个字符指针值. 内存为用户提供的字串分配, 指针因此设置.
int
long
short
uint
ulong
ushort


数组参数, 用逗号间隔的列表提供的值, 模块加载者也支持. 声明一个数组参数, 使用:
module_param_array(name, type, num, perm);
name    数组的名子(也是参数名),
type    数组元素的类型,
num    一个整型变量,
perm    通常的权限值.
如果数组参数在加载时设置, num被设置成提供的数的个数. 模块加载者拒绝比数组能放下的多的值.




hello.c
-------------------------------------------
#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
MODULE_LICENSE ("Dual BSD/GPL");

static char *who = "world";
static int times = 1;
module_param (times, int, S_IRUSR);
module_param (who, charp, S_IRUSR);


static int hello_init (void)
{
   int i;
   for (i = 0; i < times; i++)
       printk (KERN_ALERT "(%d) hello, %s!\n", i, who);
   return 0;
}

static void hello_exit (void)
{
   printk (KERN_ALERT "Goodbye, %s!\n", who);
}

module_init (hello_init);
module_exit (hello_exit);


编译生成可执行文件hello

# insmod hello who="world" times=5
#(1) hello, world!
#(2) hello, world!
#(3) hello, world!
#(4) hello, world!
#(5) hello, world!
# rmmod hello
# Goodbye,world!

注: 如果加载模块hello时,没有输入任何参数,那么who的初始值为"world",times的初始值为1

原创粉丝点击