static ssize_t my_read(struct file *f, char __user *buf, size_t
len, loff_t *off)
{
static int first=1;
printk(KERN_INFO "Driver: read()\n");
printk(KERN_INFO "Value of loff_t %ld",*off);
printk(KERN_INFO "Inside value of stringlength is %d",strlen(buffer));
if (copy_to_user(buf,buffer, 1) != 0)
return -EFAULT;
else
{
if(first<=strlen(buffer))
{
first=first+1;
printk(KERN_INFO "INside value of first is %d",first);
printk(KERN_INFO "Inside value of stringlength is %d",strlen(buffer));
return 1;
}
else
return 0;
}
}
static ssize_t my_write(struct file *f, const char __user *buf,
size_t len, loff_t *off)
{
printk(KERN_INFO "Driver: write()\n");
if (copy_from_user(buffer, buf+len-1, 1) != 0)
return -EFAULT;
else
return len;
}
However the first time I do echo -n “HEllo” and cat /dev/mynull, it prints only o and releases the device for some reason.Subsequent cat /dev/mynull returns nothing. The value of strlen(buffer) is 1.
Why is this happening? THe expected result is that Hello should be printed and strlen() should return 5.
This line in
my_write:copies 1 char from the
buf+len-1user address to the kernel buffer. That is the last char of the user string, that is, the'o'. I think it should be:And then:
just in case the user buffer is not NUL terminated.
All of that without taking into account the
offvalue, but that would depend on what exactly you want to do (maybe copy tobuffer + *off?).BTW, you should also check for buffers overruns and the like.