與內核參數交互實例

     如何與內核模塊進行參數交互,在2.6內核(include/linux/moduleparam.h)裏面進行了函數定義;

1、module_param(name, type, perm);
    name既是用戶看到的參數名,又是模塊內接受參數的變量;
    type表示參數的數據類型,是下列之一:byte, short, ushort, int, uint, long, ulong, charp, bool, invbool;
    perm指定了在sysfs中相應文件的訪問權限;訪問權限與linux文件訪問權限相同,如0777,或者使用include/linux/stat.h中定義的宏進行設置;

2、module_param_named(name, value, type, perm);
   name爲外部可見參數名,value爲源文件內部的全局變量名,即接收外部name傳入的參數;

3、module_param_string(name, string, len, perm);
    name是外部的參數名,string是內部的變量名;
    len是以string命名的buffer大小(可以小於buffer的大小,但是沒有意義);
    perm表示sysfs的訪問權限(或者perm是零,表示完全關閉相對應的sysfs項)。

    
4、module_param_array(name, type, nump, perm);
    name既是外部模塊的參數名又是程序內部的變量名;
    type是數據類型;
    perm是sysfs的訪問權限;
    指針nump指向一個整數,其值表示有多少個參數存放在數組name中。值得注意是name數組必須靜態分配。


當然,還有其他參數交互函數,如:
5、int param_set_byte(const char *val, struct kernel_param *kp);
6、int param_get_byte(char *buffer, struct kernel_param *kp);
7、......

轉載別人的實例如下:

#include <linux/module.h>
#include <linux/moduleparam.h>    /* Optional, to include module_param() macros */
#include <linux/kernel.h>    /* Optional, to include prink() prototype */
#include <linux/init.h>        /* Optional, to include module_init() macros */
#include <linux/stat.h>        /* Optional, to include S_IRUSR ... */

static int myint = -99;
static char *mystring = "i'm hungry";

static int myintary[]= {1,2,3,4};
static char *mystrary[] = {"apple", "orange", "banana"};
static int nstrs = 3;

module_param(myint, int, S_IRUSR|S_IWUSR);
MODULE_PARM_DESC(myint, "A trial integer");

module_param(mystring, charp, 0);
module_param_array(myintary, int, NULL, 0444);
module_param_array(mystrary, charp, &nstrs, 0664);

static int __init hello_init(void)
{
    int i;

    printk(KERN_INFO "myint is %d\n", myint);
    printk(KERN_INFO "mystring is %s\n", mystring);

    printk(KERN_INFO "myintary are");
    for(i = 0; i < sizeof(myintary)/sizeof(int); i++)
        printk(" %d", myintary[i]);
    printk("\n");

    printk(KERN_INFO "mystrary are");
    for(i=0; i < nstrs; i++)
        printk(" %s", mystrary[i]);
    printk("\n");

    return 0;
}

static void __exit hello_exit(void)
{
	printk(KERN_INFO "hello_exit\n");
}

MODULE_LICENSE("Dual BSD/GPL");
module_init(hello_init);
module_exit(hello_exit);





#insmod param.ko myint=100 mystring="abc" myintary=-1,-2 mystrary="a","b"

輸出如下:
myint is 100
mystring is abc
myintary are -1 -2 3 4
mystrary are a b



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章