当前位置: 首页 > news >正文

linux 内核 debugfs 使用介绍

一:概述

        debugfs 是 Linux 内核提供的一个特殊的虚拟文件系统,用于 暴露内核模块(如驱动)内部的调试信息或控制接口,供开发者、调试人员实时查看和排查问题。即 debugfs 就是一个“调试专用的 /proc 或 /sys”,方便你在不重启或不修改代码的情况下,查看内核模块的运行状态、统计信息,甚至直接向内核模块传递调试指令。

二:挂着位置和查看方式

        1. 默认挂载在 /sys/kernel/debug
        2. 如果没有挂着,可以手动挂载  sudo mount -t debugfs none /sys/kernel/debug


        3. 常见的挂载节点有:

三: 示例

        创建一个内核模块,挂载 debugfs,暴露一个文件 /sys/kernel/debug/hello_debugfs,可以用 cat 来读取内容,用 echo 向它写入数据。

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/debugfs.h>
#include <linux/uaccess.h>#define BUF_SIZE 128static struct dentry *dir_entry;
static struct dentry *file_entry;static char message[BUF_SIZE] = "Hello, debugfs!\n";// 读操作
static ssize_t hello_read(struct file *filp, char __user *buffer,size_t len, loff_t *offset)
{return simple_read_from_buffer(buffer, len, offset, message, strlen(message));
}// 写操作
static ssize_t hello_write(struct file *filp, const char __user *buffer,size_t len, loff_t *offset)
{if (len >= BUF_SIZE)return -EINVAL;if (copy_from_user(message, buffer, len))return -EFAULT;message[len] = '\0';return len;
}static const struct file_operations hello_fops = {.owner = THIS_MODULE,.read = hello_read,.write = hello_write,
};static int __init hello_debugfs_init(void)
{dir_entry = debugfs_create_dir("hello_dir", NULL);if (!dir_entry) {pr_err("Failed to create debugfs directory\n");return -ENOMEM;}file_entry = debugfs_create_file("hello_debugfs", 0666, dir_entry, NULL, &hello_fops);if (!file_entry) {pr_err("Failed to create debugfs file\n");debugfs_remove(dir_entry);return -ENOMEM;}pr_info("hello_debugfs module loaded\n");return 0;
}static void __exit hello_debugfs_exit(void)
{debugfs_remove_recursive(dir_entry);pr_info("hello_debugfs module unloaded\n");
}module_init(hello_debugfs_init);
module_exit(hello_debugfs_exit);MODULE_LICENSE("GPL");
MODULE_AUTHOR("OpenAI ChatGPT");
MODULE_DESCRIPTION("Example using debugfs");

相关文章:

  • 精益管理是什么?如何才能实现精益管理?
  • 编程中如何与AI交互-结构化输入和理解确认机制
  • Qt开发之C++泛型编程进阶
  • 使用LangChain连接远程Oracle数据库尝试LLM 提供的SQL智能助理
  • 2024jxcpc D.Magic LCM (logn筛质因子)
  • 《递归:C语言中的强大工具》
  • 【缓冲区分析】叠加分析-要素叠加
  • 时态--09--动词过去式、过去分词
  • 批量打印工具使用全攻略
  • 无需下载,免费在线AI音乐生成器:爱狐AI详解与使用
  • 基于PLC的图书管理识别系统设计
  • 2-SAT之完美塔防
  • 在 VMware 虚拟机中安装 Windows7
  • SQL实战:04之SQL中的分组问题求解
  • VPN访问SAP组服务器报登陆负载均衡错误88:无法连接到消息服务器(RC=9)
  • 机器学习day4-Knn+交叉验证api练习(预测facebook签到位置)
  • AI工具 Trae 创建java项目和配置运行环境完整示例
  • js day9
  • Lightroom 2025手机版:专业编辑,轻松上手
  • java发送邮件
  • 4月译著联合书单|心爱之物:热爱如何联结并塑造我们
  • 荆州市委书记汪元程:全市各级干部要做到慎微、慎初、慎独、慎友
  • 太好玩了!坐进大卫·霍克尼的敞篷车进入他画笔下的四季
  • 李公明|一周画记:哈佛打响第一枪
  • 清华成立人工智能医院,将构建“AI+医疗+教育+科研”闭环
  • 5145篇报道中的上海车展:40年,什么变了?