向kernel module 传递参数(Passing Arugments to Kernel Module)

在Linux中, 创建hello2.c, 文件内容如下:

#include <linux/init.h> 
#include <linux/module.h>
//step 1 include a file
#include <linux/moduleparam.h>
//step 2 create a variable
int param_var = 0;

//step 3 register (macro)
//module_param(name_var, type, permissions) : register variable name_var
module_param(param_var, int, S_IRUSR | S_IWUSR); // this variable can be read and written to

void display() {
    printk(KERN_ALERT  "Test:: param_var = %d", param_var);
}
/*
 R stands for reading, W stands for writing , X stands for execution(第三个字母(不看下划线)), USR stands for user, GRP stands for group user
   S_IRUSR
   S_IWUSR
   S_IXUSR
   S_IRGRP
   S_IWGRP
   
   S_TRUSR | S_TWUSR : sue combination
*/

stactic void hello_init(void) 
    //purpose is to register functionalities & allocate resources
    printk(KERN_ALERT "Test:: Hello world \n")
    return 0;
}

static void hello_exit(void) {
    printk(KERN_ALERT  "Test:: Good bye");
}

module_init(hello_init);
module_exit(hello_exit);

接下来, make, 编译上述文件。 我们需要切换到超级用户才可以。 sudo。


这样我们生成了module。 下面将其插入到kernel中去。 我们需要module传递参数(param_var)具体的值。

指令如下:

insmod hello2.ko  param_var = 213t6


然后我们dmsg, 则出现结果(略)。


我们也可以使用一个数组来存储我们想要存储的值, 程序如下:

hello3.c

#include <linux/init.h> 
#include <linux/module.h>
//step 1 include a file
#include <linux/moduleparam.h>
//step 2 create a variable
int param_var[3] = {0, 0, 0};

//step 3 register (macro)
//module_param(name_var, type,NULL,  permissions) : register variable name_var
module_param_array(param_var, int, 3, S_IRUSR | S_IWUSR); // this variable can be read and written to , 3 position  the number of parameters

void display() {
    printk(KERN_ALERT  "Test:: param_var = %d", param_var[0]);
    printk(KERN_ALERT  "Test:: param_var = %d", param_var[1]);
    printk(KERN_ALERT  "Test:: param_var = %d", param_var[2]);
}
/*
 R stands for reading, W stands for writing , X stands for execution(第三个字母(不看下划线)), USR stands for user, GRP stands for group user
   S_IRUSR
   S_IWUSR
   S_IXUSR
   S_IRGRP
   S_IWGRP
   
   S_TRUSR | S_TWUSR : sue combination
*/

stactic void hello_init(void) 
    //purpose is to register functionalities & allocate resources
    printk(KERN_ALERT "Test:: Hello world \n")
    return 0;
}

static void hello_exit(void) {
    printk(KERN_ALERT  "Test:: Good bye");
}

module_init(hello_init);
module_exit(hello_exit);

运行:

接下来, make, 编译上述文件。 我们需要切换到超级用户才可以。 sudo。


这样我们生成了module。 下面将其插入到kernel中去。 我们需要module传递参数(param_var)具体的值。

指令如下:

insmod hello3.ko  param_var =  12, 13,  356

等等, 步骤同上。

运行完成之后, remove the module。

rmmodule hello3.ko

然后显示: 

dmsg

显示内容略。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值