与内核参数交互实例

来源:互联网 发布:不要网络的游戏大全 编辑:程序博客网 时间:2024/05/16 14:02
     如何与内核模块进行参数交互,在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 100mystring is abcmyintary are -1 -2 3 4mystrary are a b



原创粉丝点击