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

用户空间echo写入简单字符设备模块未触发device_write问题

字符设备模块Write操作无日志输出问题排查

我在树莓派上调试字符设备模块时遇到以下问题:模块加载、卸载日志能正常出现在kernel log,但执行echo "hi" > /dev/hello或sudo bash -c 'echo "54" > /dev/chardev'等写入命令后,dmesg里看不到device_write函数中预期的“Sorry, this operation isn't supported.”日志,换多个示例代码结果一致,模块加载卸载无报错。

对应的模块代码如下:

/*
 *  chardev.c: Creates a read-only char device that says how many times
 *  you've read from the dev file
 */

#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/fs.h>
#include <asm/uaccess.h>    /* for put_user */

MODULE_LICENSE("GPL");
MODULE_AUTHOR("User");
MODULE_DESCRIPTION("A simple kernel module");
MODULE_VERSION("0.1");
/*  
 *  Prototypes - this would normally go in a .h file
 */
int init_module(void);
void cleanup_module(void);
static int device_open(struct inode *, struct file *);
static int device_release(struct inode *, struct file *);
static ssize_t device_read(struct file *, char *, size_t, loff_t *);
static ssize_t device_write(struct file *, const char *, size_t, loff_t *);

#define SUCCESS 0
#define DEVICE_NAME "chardev"   /* Dev name as it appears in /proc/devices   */
#define BUF_LEN 80      /* Max length of the message from the device */

/* 
 * Global variables are declared as static, so are global within the file. 
 */

static int Major;       /* Major number assigned to our device driver */
static int Device_Open = 0; /* Is device open?  
                 * Used to prevent multiple access to device */
static char msg[BUF_LEN];   /* The msg the device will give when asked */
static char *msg_Ptr;

static struct file_operations fops = {
    .read = device_read,
    .write = device_write,
    .open = device_open,
    .release = device_release
};

/*
 * This function is called when the module is loaded
 */
int init_module(void)
{
        Major = register_chrdev(0, DEVICE_NAME, &fops);

    if (Major < 0) {
      printk(KERN_ALERT "Registering char device failed with %d\n", Major);
      return Major;
    }

    printk(KERN_INFO "I was assigned major number %d. To talk to\n", Major);
    printk(KERN_INFO "the driver, create a dev file with\n");
    printk(KERN_INFO "'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, Major);
    printk(KERN_INFO "Try various minor numbers. Try to cat and echo to\n");
    printk(KERN_INFO "the device file.\n");
    printk(KERN_INFO "Remove the device file and module when done.\n");

    return SUCCESS;
}

/*
 * This function is called when the module is unloaded
 */
void cleanup_module(void)
{
    /* 
     * Unregister the device 
     */
    unregister_chrdev(Major, DEVICE_NAME);

}

/*
 * Methods
 */

/* 
 * Called when a process tries to open the device file, like
 * "cat /dev/mycharfile"
 */
static int device_open(struct inode *inode, struct file *file)
{
    static int counter = 0;

    if (Device_Open)
        return -EBUSY;

    Device_Open++;
    sprintf(msg, "I already told you %d times Hello world!\n", counter++);
    msg_Ptr = msg;
    try_module_get(THIS_MODULE);

    return SUCCESS;
}

/* 
 * Called when a process closes the device file.
 */
static int device_release(struct inode *inode, struct file *file)
{
    Device_Open--;      /* We're now ready for our next caller */

    /* 
     * Decrement the usage count, or else once you opened the file, you'll
     * never get get rid of the module. 
     */
    module_put(THIS_MODULE);

    return 0;
}

/* 
 * Called when a process, which already opened the dev file, attempts to
 * read from it.
 */
static ssize_t device_read(struct file *filp,   /* see include/linux/fs.h   */
               char *buffer,    /* buffer to fill with data */
               size_t length,   /* length of the buffer     */
               loff_t * offset)
{
    /*
     * Number of bytes actually written to the buffer 
     */
    int bytes_read = 0;

    /*
     * If we're at the end of the message, 
     * return 0 signifying end of file 
     */
    if (*msg_Ptr == 0)
        return 0;

    /* 
     * Actually put the data into the buffer 
     */
    while (length && *msg_Ptr) {

        /* 
         * The buffer is in the user data segment, not the kernel 
         * segment so "*" assignment won't work.  We have to use 
         * put_user which copies data from the kernel data segment to
         * the user data segment. 
         */
        put_user(*(msg_Ptr++), buffer++);

        length--;
        bytes_read++;
    }

    /* 
     * Most read functions return the number of bytes put into the buffer
     */
    return bytes_read;
}

/*  
 * Called when a process writes to dev file: echo "hi" > /dev/hello 
 */
static ssize_t
device_write(struct file *filp, const char *buff, size_t len, loff_t * off)
{
    printk(KERN_ALERT "Sorry, this operation isn't supported.\n");
    return -EINVAL;
}

排查及解决思路

1. 检查设备文件权限

普通用户默认没有设备文件的写入权限,echo命令会在用户态直接失败,根本不会触发内核的device_write回调。

  • 查看权限:ls -l /dev/chardev
  • 修复权限:执行sudo chmod 666 /dev/chardev,或者创建设备文件时直接指定权限:sudo mknod /dev/chardev c <主设备号> 0 && sudo chmod 666 /dev/chardev

2. 用更直接的命令测试写入

echo命令可能因为shell的文件打开策略(比如默认只读打开),导致写入请求没到内核。可以用dd命令强制发起写入:

sudo dd if=/dev/zero of=/dev/chardev bs=1 count=1

这个命令会明确以可写模式打开设备并写入1字节,能绕过shell的隐含限制。

3. 确认设备文件与模块匹配

确保操作的/dev/chardev确实对应加载的模块:

  • 查看模块注册的主设备号:cat /proc/devices | grep chardev
  • 对比设备文件的主设备号:ls -l /dev/chardev的第三列就是主设备号,必须和模块输出的一致。如果不一致,重新创建设备文件。

4. 检查内核日志级别

虽然KERN_ALERT是最高优先级的日志,但可以确认当前内核日志是否有过滤:

  • 查看当前日志级别:cat /proc/sys/kernel/printk,第一个数值是控制台日志级别,0表示允许所有日志输出
  • 如果级别过高,临时调整:sudo echo 0 > /proc/sys/kernel/printk

5. 改用现代字符设备注册接口

旧的register_chrdev接口在新内核中可能存在兼容性问题,建议改用alloc_chrdev_region+cdev的现代方式,示例修改如下:

#include <linux/cdev.h>

static dev_t dev_num;
static struct cdev my_cdev;

int init_module(void) {
    int ret;
    // 动态分配设备号
    ret = alloc_chrdev_region(&dev_num, 0, 1, DEVICE_NAME);
    if (ret < 0) {
        printk(KERN_ALERT "Failed to allocate chrdev region\n");
        return ret;
    }
    Major = MAJOR(dev_num);
    // 初始化字符设备结构
    cdev_init(&my_cdev, &fops);
    my_cdev.owner = THIS_MODULE;
    // 向系统添加字符设备
    ret = cdev_add(&my_cdev, dev_num, 1);
    if (ret < 0) {
        unregister_chrdev_region(dev_num, 1);
        printk(KERN_ALERT "Failed to add cdev to system\n");
        return ret;
    }
    // 打印提示信息
    printk(KERN_INFO "I was assigned major number %d. To talk to\n", Major);
    printk(KERN_INFO "the driver, create a dev file with\n");
    printk(KERN_INFO "'mknod /dev/%s c %d 0'.\n", DEVICE_NAME, Major);
    return SUCCESS;
}

void cleanup_module(void) {
    cdev_del(&my_cdev);
    unregister_chrdev_region(dev_num, 1);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.05 08:58:16