0

私は、ASCII文字列として表される正の整数Nを受け取り、それを内部に格納することを目的としたデバイスdev/my_incを作成してきました。デバイスから読み取ると、整数(N + 1)のASCII文字列表現が生成されます。

ただし、私がメッセージバッファcat /dev/my_incの前半だけmyinc_valueをユーザースペースに戻しているようです。

  • myinc_valueが48の場合、 cat /dev/my_inc4になります。

  • myinc_valueが489324、489の場合cat /dev/my_inc yields

ただし、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.

そして、シェルから呼び出されたとき:

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()を使用してメッセージ全体をコピーする方が便利で効率的です。

于 2010-04-14T23:20:06.913 に答える
1

1バイトしか表示されないのは、cに設定する前にmsg_ptrをインクリメントしているためです。c = *msg_ptr++である必要があります。またはc=* msg_ptr; msg_ptr ++; 割り当て後に増分が発生するように

于 2010-04-14T13:34:22.450 に答える