一、简介
在装载内核模块时,用户可以向模块传递参数,形式为“insmode(或 modprobe)模块名参数名=参数值”,如果不传递,参数将使用模块内定义的缺省值。如果模块被内置,就无法insmod 了,但是bootloader可以通过在 bootargs 里设置“模块名.参数名=值”的形式给该内置的模块传递参数。
二、传参的方法
2.1传递普通的参数
传递普通的参数,比如 char int 类型,使用如下函数:
函数 | module_param(name,type,perm); |
---|---|
参数 name | 要传递进去参数的名称 |
参数 type | 要传递进去参数的类型 |
参数 perm | 要传递进去参数的读写权限 |
2.2、传递数组
函数 | module_param_array(name,type,nump,perm) |
---|---|
参数 name | 要传递进去参数的名称 |
参数 type | 要传递进去参数的类型 |
参数 nump | 实际传入进去参数的个数 |
参数 perm | 要传递进去参数的读写权限 |
三、代码示例
3.1、驱动模块传普通参数
#include <linux/init.h>
#include <linux/module.h>
//定义整型变量 a
static int a;
//传递普通的参数 a,参数权限为 S_IRUSR,意为可读
module_param(a ,int,S_IRUSR);
static int hello_init(void)
{
//打印变量 a
printk("a = %d \n",a);
printk("hello world! \n");
return 0;
}
static void hello_exit(void)
{
//打印变量 a
printk("a = %d \n",a);
printk("gooodbye! \n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
3.2、驱动模块传数组
#include <linux/init.h>
#include <linux/module.h>
//定义数组 b
static int b[5];
//定义实际传入进去参数的个数
static int count;
static int a;
module_param(a ,int,S_IRUSR);
//传递数组的参数
module_param_array(b,int,&count,S_IRUSR);
static int hello_init(void)
{
int i;
//循环遍历数组 b 的值
for(i = 0;i<count;i++)
{
//打印数组 b 的值
printk("b[%d] = %d \n",i,b[i]);
}
//打印传入参数的个数
printk("count= %d \n",count);
//printk("a = %d \n",a);
//printk("hello world! \n");
return 0;
}
static void hello_exit(void)
{
printk("a = %d \n",a);
printk("gooodbye! \n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");