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

       上一节中我们我们写了一个简单的驱动程序,基本就是编程中的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文件系统可见性的掩码!

       这里我们使用模块参数,如下修改上一篇中的程序:

#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\n", hello);
	return 0;
}

static void hello_exit(void) 
{
	printk(KERN_INFO "param value:%s\n", 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");
         主要就是简单的定义了两个字符串类型的模块参数。编译!

         接下来使用:sudo insmod ./helloworld.ko 来加载模块,这个时候使用的默认参数,看输出可知道:



         接下来我们使用带参数的命令来加载,参数值为“hello”,命令为:sudo insmod ./helloworld.ko hello='hello',

看一下模块的输出:


         再来看看当我们使用参数值为“hello param”,命令为:sudo insmod ./helloworld.ko hello='hello param',

看一下模块的输出,此时会出现错误,错误如下:

         “insmod: error inserting './helloworld.ko': -1 Unknown symbol in module”。

         再利用dmesg来看一下具体的信息,如下:

         “[ 2823.124087] helloworld: Unknown parameter `param'”,从这可以看出,目前字符串参数不支持含有空字符串。

         好吧,今天就到这!




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值