You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Linux内核中如何通过DebugFS读取字符串至char数组?

解决DebugFS读取任意长度ASCII字符到内核char数组的问题

DebugFS没有提供直接绑定任意长度char数组的专用创建函数,要实现用户空间与内核字符串的交互,需要自定义file_operations结构体来处理读写逻辑,以下是完整实现方案:

完整代码示例

#include <linux/module.h>
#include <linux/debugfs.h>
#include <linux/uaccess.h>
#include <linux/string.h>

#define MAX_BUF_SIZE 256  // 可根据实际需求调整字符串缓冲区最大长度
static char str_buf[MAX_BUF_SIZE] = {0};
static struct dentry *dir;

// 用户空间读取内核字符串缓冲区
static ssize_t str_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)
{
    return simple_read_from_buffer(buf, count, ppos, str_buf, strlen(str_buf));
}

// 用户空间写入字符串到内核缓冲区
static ssize_t str_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)
{
    // 限制写入长度,避免缓冲区溢出,预留'\0'空间
    if (count > MAX_BUF_SIZE - 1) {
        count = MAX_BUF_SIZE - 1;
    }

    // 从用户空间拷贝数据到内核,处理拷贝错误
    if (copy_from_user(str_buf, buf, count)) {
        return -EFAULT;
    }

    // 确保字符串以'\0'结尾,符合C字符串规范
    str_buf[count] = '\0';
    *ppos += count;
    return count;
}

// 自定义文件操作集合
static const struct file_operations str_fops = {
    .owner = THIS_MODULE,
    .read = str_read,
    .write = str_write,
};

int init_module(void)
{
    struct dentry *junk;

    // 创建debugfs目录
    dir = debugfs_create_dir("example", 0);
    if (!dir) {
        printk(KERN_ALERT "Failed to create /sys/kernel/debug/example\n");
        return -1;
    }

    // 创建自定义字符串文件,关联file_operations
    junk = debugfs_create_file("my_string", 0666, dir, NULL, &str_fops);
    if (!junk) {
        printk(KERN_ALERT "Failed to create /sys/kernel/debug/example/my_string\n");
        debugfs_remove_recursive(dir);  // 创建失败时清理已创建的目录
        return -1;
    }

    return 0;
}

void cleanup_module(void)
{
    debugfs_remove_recursive(dir);
}

MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("DebugFS String Example");

关键说明

  • 缓冲区大小控制:通过MAX_BUF_SIZE限制内核缓冲区长度,避免内存溢出,可根据实际场景调整数值
  • 用户空间数据拷贝:必须使用copy_from_user/copy_to_user安全拷贝用户空间数据,直接访问用户内存会导致内核崩溃
  • 字符串合法性:写入时手动添加'\0',确保内核中存储的是合法的C字符串,避免后续字符串操作出错
  • 错误处理:创建文件失败时需调用debugfs_remove_recursive清理已创建的目录,避免残留资源
  • 权限设置:0666权限允许所有用户读写,实际使用中应遵循最小权限原则,根据需求调整权限位

内容的提问来源于stack exchange,提问作者GossamerClaw3045

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 16:12:39