can't read from the device driver using read() function.
Hi,
I was writing a sample character device driver, when I try to test it with the sample user application I was successfully able to write to the device but while trying to read from the device it flashing error “bad file descriptor”. Does anybody have some idea about this?
My driver read and write code is as below
ssize_t memory_read(struct file *filp, char *buf, size_t count, loff_t *f_pos) {
ssize_t retval = 0;
printk(KERN_INFO MODULE_NAME":- The device file is read\n");
struct mem_dev *dev = filp->private_data;
printk(KERN_INFO MODULE_NAME":- the dev->size value is: %ld\n", dev->size);
if (*f_pos >= dev->size)
goto out;
if (*f_pos + count > dev->size)
count = dev->size - *f_pos;
/* Transfering data to user space */
if (copy_to_user(buf, memory_buffer, count)) {
retval = -EFAULT;
goto out;
}
*f_pos += count;
retval = count;
return retval;
out:
return retval;
}
ssize_t memory_write( struct file *filp, char *buf, size_t count, loff_t *f_pos) {
printk(KERN_INFO MODULE_NAME":- The device file is Written\n");
struct mem_dev *dev = filp->private_data;
ssize_t retval = -ENOMEM; /* value used in "goto out" statements */
if (copy_from_user(memory_buffer, buf, count)) {
retval = -EFAULT;
goto out;
}
*f_pos += count;
retval = count;
/* update the size */
if (dev->size < *f_pos)
dev->size = *f_pos;
printk(KERN_INFO MODULE_NAME":- the return value is: %ld\n", retval);
return retval;
out:
return retval;
}
my sample user application is as follows.
fp = open("/dev/test_memory",777);
if(fp < 0) {
printf("Unable to open the device\n");
return 1;
} else {
printf("Device open success\n");
buf = (char *)malloc(100);
printf("Enter the characters to write to device file: ");
scanf("%s", buf);
ret = write(fp,buf,strlen(buf));
if(ret < 0){
printf("Unable to write to device, response: %d\n",ret);
} else {
out_buf = (char *)malloc(100);
ret = read(fp,out_buf,strlen(buf));
if(ret < 0){
printf("Unable to read from device, response: %d\n",ret);
} else {
printf("The device content read is: %s\n",out_buf);
}
free(out_buf);
}
free(buf);
close(fp);
}
return 0;
}
TIA
|