x4412开发板&ibox卡片电脑项目实战17-模块传参实验

在很多情况下,在加载驱动时我们需要接收外部的指令。我们可以通过加载模块传递参数的方式实现。在驱动中,通过“module_param(参数名,参数类型,参数读/写权限)”为模块定义一个参数,在加载模块时,向其传递参数。如果不传递,则参数为驱动中定义的默认值。

参数类型可以是 byte、short、ushort、int、uint、long、ulong、charp(字符指针)、bool 或 invbool(布尔的反),在模块被编译时会将module_param中声明的类型与变量定义的类型进行比较,判断是否一致。

在上一章节编写的hello x4412驱动模块中,修改hello-x4412.c文件,内容如下:

#include <linux/module.h>
#include <linux/init.h>
 
static char *str = "This is a simple characterdriver";
static int count = 12345;
 
module_param(str,charp,0644);
MODULE_PARM_DESC(str,"a stringvariable");
 
module_param(count,int,0644);
MODULE_PARM_DESC(str,"a integervariable");
 
static int __devinit hello_x4412_init(void)
{
         printk("string:%s\r\n",str);
         printk("count:%d\r\n",count);
         return0;
}
 
static void hello_x4412_exit(void)
{
         printk("Goodbye,x4412!\r\n");
}
 
module_init(hello_x4412_init);
module_exit(hello_x4412_exit);
 
MODULE_LICENSE("GPL");
MODULE_VERSION("1.0");
MODULE_AUTHOR("www.9tripod.com");
MODULE_ALIAS("a character driversample");
MODULE_DESCRIPTION("hello x4412 driver");

       程序清单定义了两个默认的参数str和count,初赋予了默认的值。我们编译成KO文件后,不传递任何参数加载模块:

[root@x4412 mnt]# insmod hello-x4412.ko
[ 1461.196000] string:This is a simple characterdriver
[ 1461.199606] count:12345
[root@x4412 mnt]#

       传递参数加载模块:

[root@x4412 mnt]# rmmod hello-x4412.ko
[ 1746.059685] Goodbye,x4412!
[root@x4412 mnt]# insmod hello-x4412.kostr='www.9tripod.com' count=54321
[ 1786.885420] string:www.9tripod.com
[ 1786.887461] count:54321
[root@x4412 mnt]#

       可见,在加载模块时我们定义的str字符串和整形变量count被传进内核,并打印出来了。

       当模块被加载后,在/sys/module/目录下将出现以此模块名命名的目录。由于模块声明了module_param参数,在此模块的目录下还将出现 parameters目录,包含一系列以参数名命名的文件节点,这些文件的权限值就是传入module_param()的“参数读/写权限”,而文件的内容为参数的值:

[root@x4412 parameters]# pwd
/sys/module/hello_x4412/parameters
[root@x4412 parameters]# ls
count  str
[root@x4412 parameters]# more count
54321
[root@x4412 parameters]# more str
www.9tripod.com
[root@x4412 parameters]#

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值