module_param()用法

來源:互聯網
上載者:User
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)

其中使用了 3 個參數:要傳遞的參數變數名, 變數的資料類型, 以及訪問參數的許可權。

<<<

perm參數的作用是什麼。

最後的 module_param 欄位是一個許可權值,表示此參數在sysfs檔案系統中所對應的檔案節點的屬性。你應當使用 <linux/stat.h> 中定義的值. 這個值控制誰可以存取這些模組參數在 sysfs 中的表示.當perm為0時,表示此參數不存在 sysfs檔案系統下對應的檔案節點。 否則, 模組被載入後,在/sys/module/ 目錄下將出現以此模組名命名的目錄, 帶有給定的許可權.。
許可權在include/linux/stat.h中有定義
比如:
#define S_IRWXU 00700
#define S_IRUSR 00400
#define S_IWUSR 00200
#define S_IXUSR 00100

#define S_IRWXG 00070
#define S_IRGRP 00040
#define S_IWGRP 00020
#define S_IXGRP 00010

#define S_IRWXO 00007
#define S_IROTH 00004
#define S_IWOTH 00002
#define S_IXOTH 00001

使用 S_IRUGO 作為參數可以被所有人讀取, 但是不能改變; S_IRUGO|S_IWUSR 允許 root 來改變參數. 注意, 如果一個參數被 sysfs 修改, 你的模組看到的參數值也改變了, 但是你的模組沒有任何其他的通知. 你應當不要使模組參數可寫, 除非你準備好檢測這個改變並且因而作出反應.

>>>

這個宏定義應當放在任何函數之外, 典型地是出現在源檔案的前面.定義如:

static char *whom = "world";
static int howmany = 1;
module_param(howmany, int, S_IRUGO);
module_param(whom, charp, S_IRUGO);

模組參數支援許多類型: bool
invbool 一個布爾型( true 或者 false)值(相關的變數應當是 int 類型). invbool 類型顛倒了值, 所以真值變成 false, 反之亦然. charp :一個字元指標值. 記憶體為使用者提供的字串分配, 指標因此設定. int
long
short
uint
ulong
ushort 基本的變長整型值. 以 u 開頭的是無符號值.
數組參數, 用逗號間隔的列表提供的值, 模組載入者也支援. 聲明一個數組參數, 使用:
module_param_array(name,type,num,perm);
這裡 name 是你的數組的名子(也是參數名), type 是數組元素的類型, num 是一個整型變數, perm 是通常的許可權值. 如果數組參數在載入時設定, num 被設定成提供的數的個數. 模組載入者拒絕比數組能放下的多的值. 測試模組,來源程式hello.c內容如下: #include <linux/init.h> #include <linux/module.h>
#include <linux/moduleparam.h>         MODULE_LICENSE("Dual BSD/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 who="world" times=5 出現5次"hello,world!": #(1)hello,world! #(2)hello,world! #(3)hello,world! #(4)hello,world! #(5)hello,world! 卸載: # rmmod hello 出現: #Goodbye,world!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.