2. 请简述内核模块程序的结构,并根据该结构编写一个内核模块:要求加载模块时内核日志中显示每位同学的学号,卸载时显示“bye-embedded”
时间: 2024-02-01 10:16:02 浏览: 35
内核模块程序的结构通常由以下几部分组成:
1. 头文件:包含模块所需的头文件,如 linux/module.h 和 linux/init.h 等。
2. 模块参数:定义模块的参数,可以通过 insmod 命令传递给模块。
3. 初始化函数:当模块被加载时,会自动调用初始化函数进行模块的初始化。
4. 卸载函数:当模块被卸载时,会自动调用卸载函数进行模块的清理。
下面是一个简单的内核模块示例,可以输出每位同学的学号:
```c
#include <linux/module.h>
#include <linux/init.h>
static char *student_id = "12345678"; // 学号
module_param(student_id, charp, 0644); // 定义模块参数
static int __init hello_init(void)
{
printk(KERN_INFO "Hello, %s\n", student_id);
return 0;
}
static void __exit hello_exit(void)
{
printk(KERN_INFO "Goodbye, %s\n", student_id);
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple Hello World module");
```
在模块初始化函数 hello_init 中,使用 printk 函数输出学号信息。在模块卸载函数 hello_exit 中,同样使用 printk 函数输出 goodbye 信息。注意,在模块参数 student_id 定义时,使用了 module_param 宏来定义了一个名为 student_id 的模块参数,类型为 charp,权限为 0644。这样,我们就可以在 insmod 命令中传递参数,例如:
```
sudo insmod hello.ko student_id="87654321"
```
当我们加载模块时,在内核日志中会输出类似如下的信息:
```
Hello, 87654321
```
当我们卸载模块时,在内核日志中会输出类似如下的信息:
```
Goodbye, 87654321
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)