Linux设备驱动之Hello World带参数版本!


上一节中我们我们写了一个简单的驱动程序(见  ),基本就是编程中的hello world!但是整个打印出来的内容都是编译的时候确定好的,不能根据输入的参数动态改变。所以,这里我们实现hello world!带参数的版本,主要实现的效果就是装载模块的时候给出打印参数,模块能够打印出这个参数!

参数的来源主要有两个:一是使用insmod ./XX.ko 时候在命令行后直接给出参数;二是使用modprobe命令装载模块时可以从它的配置文件文件中读取参数值!当不通过这两个方式提供参数值时,参数会使用我们在模块中提供的默认值。所有的参数必须使用module_param这个宏来定义:

  1. /** 
  2.  * module_param - typesafe helper for a module/cmdline parameter 
  3.  * @value: the variable to alter, and exposed parameter name. 
  4.  * @type: the type of the parameter 
  5.  * @perm: visibility in sysfs. 
  6.  **/  
  7.  #define module_param(name, type, perm)             \   
  8.     module_param_named(name, name, type, perm)

由上面的定义可以看出,定义一个参数需要三分部分:参数的名称、参数的类型和参数在sysfs文件系统入口可见性的掩码。

模块装载器也支持数组参数,定义如下:

  1. /** 
  2.  * module_param_array - a parameter which is an array of some type 
  3.  * @name: the name of the array variable 
  4.  * @type: the type, as per module_param() 
  5.  * @nump: optional pointer filled in with the number written 
  6.  * @perm: visibility in sysfs 
  7.  **/  
  8. #define module_param_array(name, type, nump, perm)      \   
  9.     module_param_array_named(name, name, type, nump, perm)

定义一个参数数组需要四个部分:数组的名称、数组元素的类型、数组的大小以及数组参数在sysfs文件系统可见性的掩码!

这里我们使用模块参数,如下修改上一篇《Linux设备驱动之Hello World! 》中的程序:

  1. #include <linux/init.h>   
  2. #include <linux/module.h>   
  3.   
  4. static char *hello = "hello world!";  
  5. static char *bye = "goodbye!";  
  6.   
  7. static int hello_init(void)   
  8. {  
  9.     printk(KERN_INFO "param vlaue:%s\n", hello);  
  10.     return 0;  
  11. }  
  12.   
  13. static void hello_exit(void)   
  14. {  
  15.     printk(KERN_INFO "param value:%s\n", bye);  
  16. }  
  17.   
  18. module_init(hello_init);  
  19. module_exit(hello_exit);  
  20. module_param(hello, charp, S_IRUGO);  
  21. module_param(bye, charp, S_IRUGO);  
  22.   
  23. MODULE_LICENSE("Dual BSD/GPL");  
  • 1
  • 2
  • 下一页

相关内容