歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> Linux 驅動開發之內核模塊開發 (三)—— 模塊傳參

Linux 驅動開發之內核模塊開發 (三)—— 模塊傳參

日期:2017/3/3 11:49:15   编辑:Linux技術
一、module_param() 定義
通常在用戶態下編程,即應用程序,可以通過main()的來傳遞命令行參數,而編寫一個內核模塊,則通過module_param() 來傳參。
module_param()宏是Linux 2.6內核中新增的,該宏被定義在include/linux/moduleparam.h文件中,具體定義如下:
#define module_param(name, type, perm) module_param_named(name, name, type, perm)
所以我們通過宏module_param()定義一個模塊參數:
module_param(name, type, perm);
參數的意義:
name 既是用戶看到的參數名,又是模塊內接受參數的變量;
type 表示參數的數據類型,是下列之一:byte, short, ushort, int, uint, long, ulong, charp, bool, invbool;
perm 指定了在sysfs中相應文件的訪問權限。訪問權限與linux文件訪問權限相同的方式管理,如0644,或使用stat.h中的宏如S_IRUGO表示。
0表示完全關閉在sysfs中相對應的項。
二、module_param() 使用方法
module_param()宏不會聲明變量,因此在使用宏之前,必須聲明變量,典型地用法如下:
static unsigned int int_var = 0;
module_param(int_var, uint, S_IRUGO);
這些必須寫在模塊源文件的開頭部分。即int_var是全局的。也可以使模塊源文件內部的變量名與外部的參數名有不同的名字,通過module_param_named()定義。
a -- module_param_named()
module_param_named(name, variable, type, perm);
name 外部(用戶空間)可見的參數名;
variable 源文件內部的全局變量名;
type 類型
perm 權限
而module_param通過module_param_named實現,只不過name與variable相同。
例如:
static unsigned int max_test = 9;
module_param_name(maximum_line_test, max_test, int, 0);
b -- 字符串參數
如果模塊參數是一個字符串時,通常使用charp類型定義這個模塊參數。內核復制用戶提供的字符串到內存,並且相對應的變量指向這個字符串。
例如:
static char *name;
module_param(name, charp, 0);
另一種方法是通過宏module_param_string()讓內核把字符串直接復制到程序中的字符數組內。
module_param_string(name, string, len, perm);
這裡,name是外部的參數名,string是內部的變量名,len是以string命名的buffer大小(可以小於buffer的大小,但是沒有意義),perm表示sysfs的訪問權限(或者perm是零,表示完全關閉相對應的sysfs項)。
例如:
static char species[BUF_LEN];
module_param_string(specifies, species, BUF_LEN, 0);
c -- 數組參數
數組參數, 用逗號間隔的列表提供的值, 模塊加載者也支持. 聲明一個數組參數, 使用:
module_param_array(name, type, num, perm);
name 數組的名子(也是參數名),
type 數組元素的類型,
num 一個整型變量,
perm 通常的權限值.
如果數組參數在加載時設置, num被設置成提供的數的個數. 模塊加載者拒絕比數組能放下的多的值。
三、使用實例
[cpp] view
plain copy





#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
MODULE_LICENSE ("GPL");
static char *who = "world";
static int times = 1;
module_param (times, int, S_IRUSR);
module_param (who, charp, S_IRUSR);
static int hello_init (void)
{
int i;
for (i = 0; i < times; i++)
printk (KERN_ALERT "(%d) hello, %s!\n", i, who);
return 0;
}
static void hello_exit (void)
{
printk (KERN_ALERT "Goodbye, %s!\n", who);
}
module_init (hello_init);
module_exit (hello_exit);
編譯生成可執行文件hello
# insmod hello.ko who="world" times=5
[cpp] view
plain copy





#(1) hello, world!
#(2) hello, world!
#(3) hello, world!
#(4) hello, world!
#(5) hello, world!
# rmmod hello
# Goodbye,world!
注:
a -- 如果加載模塊hello時,沒有輸入任何參數,那麼who的初始值為"world",times的初始值為1

b -- 同時向指針傳遞字符串的時候,不能傳遞這樣的字符串 who="hello world!".即字符串中間不能有空格

c --/sys/module/hello/parameters 該目錄下生成變量對應的文件節點
Copyright © Linux教程網 All Rights Reserved