0

我一直在写一个设备dev/my_inc,它的意思是把一个正整数N表示为一个 ASCII 字符串,并在内部存储它。从设备读取的任何内容都应生成整数(N+1)的 ASCII 字符串表示形式。

但是,当 I 时cat /dev/my_inc,我似乎只是将myinc_value消息缓冲区的前半部分返回到用户空间。

  • 如果myinc_value是 48,则cat /dev/my_inc产生 4。

  • 如果myinc_value是 489324, cat /dev/my_inc yields489。

但是,bytes_read表示整个消息已复制到用户空间。这是dmesg的输出:

[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.

当从 shell 调用时:

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;
}
4

2 回答 2

2

可能 put_user() 被定义为一个宏,以便在

if(put_user(c, buffer++))

搞砸了-尽管我不明白它如何解释您所看到的。

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

于 2010-04-14T23:20:06.913 回答
1

它只显示 1 个字节的原因是因为您在将 msg_ptr 设置为等于 c 之前递增它。它需要是 c = *msg_ptr++; 或 c = *msg_ptr; msg_ptr++; 以便在分配之后发生增量

于 2010-04-14T13:34:22.450 回答