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

来源:互联网 发布:鼓浪屿酒店推荐 知乎 编辑:程序博客网 时间:2024/06/07 15:03

在很多情况下,在加载驱动时我们需要接收外部的指令。我们可以通过加载模块传递参数的方式实现。在驱动中,通过“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]# lscount  str[root@x4412 parameters]# more count54321[root@x4412 parameters]# more strwww.9tripod.com[root@x4412 parameters]#

0 0
原创粉丝点击