我该怎么添加一个内核全局变量
时间: 2023-12-03 15:07:11 浏览: 61
要添加一个内核全局变量,你需要在内核代码中定义一个全局变量,并将其声明为`extern`。然后,在需要使用这个全局变量的函数中,你可以直接使用它。
以下是一个示例代码,展示如何添加一个名为`my_global_var`的全局变量:
```c
#include <linux/module.h>
#include <linux/kernel.h>
// 声明全局变量
extern int my_global_var;
// 定义全局变量
int my_global_var = 0;
int init_module(void)
{
pr_info("The value of my_global_var is: %d\n", my_global_var);
return 0;
}
void cleanup_module(void)
{
pr_info("Goodbye, world!\n");
}
```
在这个示例中,我们声明了一个名为`my_global_var`的全局变量,并将其定义为0。在`init_module`函数中,我们打印了这个全局变量的值。在这个例子中,它将会是0。
要将这个示例编译成内核模块,你可以使用如下Makefile:
```makefile
obj-m += my_module.o
all:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean
```
编译完成后,你可以将其加载到内核中,并查看输出:
```bash
$ sudo insmod my_module.ko
$ dmesg | tail
[ 1913.048866] The value of my_global_var is: 0
$ sudo rmmod my_module
$ dmesg | tail
[ 1913.048866] The value of my_global_var is: 0
[ 1919.418855] Goodbye, world!
```
在这个输出中,我们可以看到`my_global_var`的值为0,并且在卸载模块时,`cleanup_module`函数被调用。