在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
显示内容略。