代码之家  ›  专栏  ›  技术社区  ›  Rob

Linux设备驱动程序-我的设备有什么问题?

  •  0
  • Rob  · 技术社区  · 15 年前

    我一直在写一个装置 Dev/ Myyin公司 这意味着取一个正整数 n 表示为ascii字符串,并在内部存储。从设备中读取的任何内容都应该产生整数的ascii字符串表示形式 (n+1) .

    但是,当我 cat /dev/my_inc ,我似乎只得到了 myinc_value 返回用户空间的消息缓冲区。

    • 如果 MycIn值 是48, CAT/dev/my_公司 收益率为4。

    • 如果 MycIn值 是489324, cat /dev/my_inc yields 489。

    然而, bytes_read 指示已将整个邮件复制到用户空间。这是来自 启动信息 :

    [54471.381170] my_inc opened with initial value 489324 = 489324.
    [54471.381177] my_inc device_read() called with value 489325 and msg 489324.
    [54471.381179] my_inc device_read() read 4.
    [54471.381182] my_inc device_read() read 8.
    [54471.381183] my_inc device_read() read 9.
    [54471.381184] my_inc device_read() read 3.
    [54471.381185] my_inc device_read() read 2.
    [54471.381186] my_inc device_read() read 5. my_inc device_read() returning 7.
    [54471.381192] my_inc device_read() called with value 489325 and msg 489325.
    

    当从外壳调用时:

    root@rbst:/home/rob/myinc_mod# cat /dev/my_inc
    489
    

    来源:

    // Read from the device
    //
    static ssize_t device_read(struct file * filp, char * buffer, 
        size_t length, loff_t * offset)
    {
        char c;
        int bytes_read = 0;
        int value = myinc_value + 1;
    
        printk(KERN_INFO "my_inc device_read() called with value %d and msg %s.\n", 
            value, msg);
    
        // Check for zero pointer
        if (*msg_ptr == 0) 
        {
            return 0;
        }
        // Put the incremented value in msg 
        snprintf(msg, MAX_LENGTH, "%d", value);
    
        // Copy msg into user space
        while (length && *msg_ptr) 
        {
            c = *(msg_ptr++);
            printk(KERN_INFO "%s device_read() read %c. ", DEV_NAME, c);
            if(put_user(c, buffer++))
            {
                return -EFAULT;
            }
            length--;
            bytes_read++;
        }
    
        // Nul-terminate the buffer
        if(put_user('\0', buffer++))
        {
            return -EFAULT;
        }
        bytes_read++;
        printk("my_inc device_read() returning %d.\n", bytes_read);
        return bytes_read;
    }
    
    2 回复  |  直到 13 年前
        1
  •  2
  •   Dipstick    15 年前

    可能是将put_user()定义为宏,以便

    if(put_user(c, buffer++))
    

    搞砸了-虽然我不知道它怎么解释你看到的。

    无论如何,使用copy_to_user()复制整个msg会更方便、更高效。

        2
  •  1
  •   Nuri Crayton    15 年前

    它只显示1个字节的原因是,在将msg_ptr设置为c之前,您正在递增它。它需要是c=*msg_ptr++;或c=*msg_ptr;msg_ptr++;以便在赋值之后递增。