上一节中我们我们写了一个简单的驱动程序(见 http://www.linuxidc.com/Linux/2012-03/55913.htm ),基本就是编程中的hello world!但是整个打印出来的内容都是编译的时候确定好的,不能根据输入的参数动态改变。所以,这里我们实现hello world!带参数的版本,主要实现的效果就是装载模块的时候给出打印参数,模块能够打印出这个参数!参数的来源主要有两个:一是使用insmod ./XX.ko 时候在命令行后直接给出参数;二是使用modprobe命令装载模块时可以从它的配置文件文件中读取参数值!当不通过这两个方式提供参数值时,参数会使用我们在模块中提供的默认值。所有的参数必须使用module_param这个宏来定义:
- /**
- * module_param - typesafe helper for a module/cmdline parameter
- * @value: the variable to alter, and exposed parameter name.
- * @type: the type of the parameter
- * @perm: visibility in sysfs.
- **/
- #define module_param(name, type, perm)
- module_param_named(name, name, type, perm)
由上面的定义可以看出,定义一个参数需要三分部分:参数的名称、参数的类型和参数在sysfs文件系统入口可见性的掩码。模块装载器也支持数组参数,定义如下:
- /**
- * module_param_array - a parameter which is an array of some type
- * @name: the name of the array variable
- * @type: the type, as per module_param()
- * @nump: optional pointer filled in with the number written
- * @perm: visibility in sysfs
- **/
- #define module_param_array(name, type, nump, perm)
- module_param_array_named(name, name, type, nump, perm)
定义一个参数数组需要四个部分:数组的名称、数组元素的类型、数组的大小以及数组参数在sysfs文件系统可见性的掩码!这里我们使用模块参数,如下修改上一篇《Linux设备驱动之Hello World! 》中的程序:
- #include <linux/init.h>
- #include <linux/module.h>
-
- static char *hello = "hello world!";
- static char *bye = "goodbye!";
-
- static int hello_init(void)
- {
- printk(KERN_INFO "param vlaue:%s
", hello);
- return 0;
- }
-
- static void hello_exit(void)
- {
- printk(KERN_INFO "param value:%s
", bye);
- }
-
- module_init(hello_init);
- module_exit(hello_exit);
- module_param(hello, charp, S_IRUGO);
- module_param(bye, charp, S_IRUGO);
-
- MODULE_LICENSE("Dual BSD/GPL");