我一直在写一个设备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 yields
489。
但是,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;
}