Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 驅動開發(三):用 module_param 為內核模塊傳參

一、module_param() 定義

使用者態程式可以透過 main() 的參數傳值,而內核模塊則要用 module_param()。這個宏是 Linux 2.6 新增的,定義在 include/linux/moduleparam.h:

#define module_param(name, type, perm) \
        module_param_named(name, name, type, perm)

使用方式:

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() 不會宣告變數,所以使用前必須自己宣告,且通常寫在源檔開頭(即變數為全域):

static unsigned int int_var = 0;
module_param(int_var, uint, S_IRUGO);

a. 讓外部參數名與內部變數名不同

module_param_named(name, variable, type, perm);

name 是外部可見名稱,variable 是源檔內的全域變數。module_param 其實就是兩者同名的特例。

static unsigned int max_test = 9;
module_param_named(maximum_line_test, max_test, int, 0);

b. 字串參數

用 charp 時,內核會把使用者提供的字串複製到記憶體,變數指向該字串:

static char *name;
module_param(name, charp, 0);

另一種做法是讓內核直接複製到你的字元陣列:

module_param_string(name, string, len, perm);

name 是外部參數名,string 是內部變數,len 是該 buffer 大小。

static char species[BUF_LEN];
module_param_string(species, species, BUF_LEN, 0);

c. 陣列參數

載入時以逗號分隔的清單提供數值:

module_param_array(name, type, num, perm);

name 是陣列名(也是參數名),type 是元素型別,num 是一個整數變數,載入時會被設成實際提供的元素個數;perm 為一般權限值。若提供的值超過陣列容量,載入器會拒絕。

三、實例

#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);

載入時傳參:

insmod hello.ko who="world" times=5

輸出:

(1) hello, world!
(2) hello, world!
(3) hello, world!
(4) hello, world!
(5) hello, world!

rmmod hello
Goodbye, world!

幾點注意:

a. 載入時不給參數,who 保持 "world"、times 保持 1;
b. 傳字串時內容不能含空格,例如 who="hello world!" 是行不通的;
c. /sys/module/hello/parameters 下會產生對應的變數節點。

Copyright © Linux教程網 All Rights Reserved