实验八 添加/proc文件系统
8.1 实验目的
通过加载内核模块,为/proc文件系统创建以下内容:
一个名叫proc_test的子目录。
一个名叫current的文件,只读,读出的内容是读它的进程的情况。
一个名叫current_too的链接,指向current。
一个名叫hello的文件,可读可写。读出的内容是上次写的内容前面加两句话。
8.2 实验步骤
(1)在虚拟机里面手动创建pro文件目录,如图3.1所示
图8.1 手动创建pro文件目录
(2)编写proc_test.c文件,代码如下:
#include <linux/sched.h>
#include <linux/init_task.h>
#include <linux/module.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/uaccess.h>
#define MAX_LENGTH 1024
static char hello_content[MAX_LENGTH] = "hello world\n"; // 初始化一个长度为 1024 的字符数组,并赋值 "hello world\n"
//用于处理对 /proc/proc_test/hello 文件的写操作。它从用户空间接收数据并将其复制到内核空间的 hello_content 数组中,偏移量为12。如果写入的字符数超过了数组长度,会返回错误。
static ssize_t hello_proc_write(struct file *file, const char __user *buffer, size_t count, loff_t *pos) {
if (count > MAX_LENGTH - 1) // 如果写入的字符数大于 MAX_LENGTH - 1,则返回错误
return -EINVAL;
if (copy_from_user(hello_content + 12, buffer, count)) // 将用户空间的数据复制到内核空间的 hello_content 数组中,偏移量为 12
return -EFAULT;
hello_content[count + 12