九鼎创展论坛

标题: x4412&ibox项目实战17-模块传参实验 [打印本页]

作者: armeasy    时间: 2014-9-26 17:23
标题: x4412&ibox项目实战17-模块传参实验
在很多情况下,在加载驱动时我们需要接收外部的指令。我们可以通过加载模块传递参数的方式实现。在驱动中,通过“module_param(参数名,参数类型,参数读/写权限)”为模块定义一个参数,在加载模块时,向其传递参数。如果不传递,则参数为驱动中定义的默认值。
参数类型可以是 byte、short、ushort、int、uint、long、ulong、charp(字符指针)、bool 或 invbool(布尔的反),在模块被编译时会将module_param中声明的类型与变量定义的类型进行比较,判断是否一致。
在上一章节编写的hello x4412驱动模块中,修改hello-x4412.c文件,内容如下:
  1. #include <linux/module.h>
  2. #include <linux/init.h>

  3. static char *str = "This is a simple character driver";
  4. static int count = 12345;

  5. module_param(str,charp,0644);
  6. MODULE_PARM_DESC(str,"a string variable");

  7. module_param(count,int,0644);
  8. MODULE_PARM_DESC(str,"a integer variable");

  9. static int __devinit hello_x4412_init(void)
  10. {
  11.          printk("string:%s\r\n",str);
  12.          printk("count:%d\r\n",count);
  13.          return 0;
  14. }

  15. static void hello_x4412_exit(void)
  16. {
  17.          printk("Goodbye,x4412!\r\n");
  18. }

  19. module_init(hello_x4412_init);
  20. module_exit(hello_x4412_exit);

  21. MODULE_LICENSE("GPL");
  22. MODULE_VERSION("1.0");
  23. MODULE_AUTHOR("www.9tripod.com");
  24. MODULE_ALIAS("a character driver sample");
  25. MODULE_DESCRIPTION("hello x4412 driver");
复制代码
       程序清单定义了两个默认的参数strcount,初赋予了默认的值。我们编译成KO文件后,不传递任何参数加载模块:
  1. [root@x4412 mnt]# insmod hello-x4412.ko
  2. [ 1461.196000] string:This is a simple character driver
  3. [ 1461.199606] count:12345
  4. [root@x4412 mnt]#
复制代码
       传递参数加载模块:
  1. [root@x4412 mnt]# rmmod hello-x4412.ko
  2. [ 1746.059685] Goodbye,x4412!
  3. [root@x4412 mnt]# insmod hello-x4412.ko str='www.9tripod.com' count=54321
  4. [ 1786.885420] string:www.9tripod.com
  5. [ 1786.887461] count:54321
  6. [root@x4412 mnt]#
复制代码
       可见,在加载模块时我们定义的str字符串和整形变量count被传进内核,并打印出来了。

附做好的hello-x4412.ko文件,可直接在x4412开发板或ibox卡片电脑上测试:
hello-x4412.ko (3.34 KB, 下载次数: 5)

作者: zhengxi    时间: 2014-10-28 21:56
需要好好看看才知道啊
作者: huxh5837    时间: 2014-11-21 17:45
不错,mark,支持楼主




欢迎光临 九鼎创展论坛 (http://bbs.9tripod.com/) Powered by Discuz! X3.2