私は、ASCII文字列として表される正の整数Nを受け取り、それを内部に格納することを目的としたデバイスdev/my_incを作成してきました。デバイスから読み取ると、整数(N + 1)のASCII文字列表現が生成されます。
ただし、私がメッセージバッファcat /dev/my_inc
の前半だけmyinc_value
をユーザースペースに戻しているようです。
myinc_value
が48の場合、cat /dev/my_inc
4になります。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;
}