NaN
NaN

Reputation: 3591

linux virtual file as device driver

I write a linux char device driver to simulate a file. The data is stored in an array and I want to implement a "read-file"-handler...

static ssize_t data_read(struct file *f, char __user *buf, size_t count, loff_t *f_pos){
char *msg_pointer;
int bytes_read = 0;

if(vault.storage==NULL)
    return -EFAULT;

msg_pointer = vault.storage + *f_pos;

while (count && (*f_pos < vault.size) ) {
    put_user(*(msg_pointer++), buf++);
    count--;
    bytes_read++;
    ++*f_pos;
}

return bytes_read;
}

vault.storage is a pointer to a kmalloc-creation. If I test the code by copying with dd it works as expected, but when I want to open the file with C

if((fp_data = open("/dev/vault0", O_RDWR)) < 0){
    perror("could not open file.\n");
}

err = write(fp_data, "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890", 36);

if (err < 0){
    perror("failed to write to sv \n");
} 

read(fp_data, buffer, 36);
read(fp_data, buffer, 36);

the first read-command returns 4.. the second 0 - how is this possible?

Upvotes: 2

Views: 1373

Answers (2)

rulingminds
rulingminds

Reputation: 176

Put a printk in the data_read call and print the count and print what is returned to the user(check the value of bytes_read). The bytes_read is returned to the read() call in the use space. Make sure you are returning correct value. And you can also print the fpos and check what is happening.

Here I assume that your drivers read and write functions are called properly, I mean major and minor numbers of your device file belongs to your driver

Upvotes: 0

Jason
Jason

Reputation: 32538

write performed on a file is not guaranteed to write all the bytes requested atomically ... that is only reserved for a pipe or FIFO when the requested write-amount is less than PIPE_BUF in size. For instance, write can be interrupted by a signal after writing some bytes, and there will be other instances where write will not output the full number of requested bytes before returning. Therefore you should be testing the number of bytes written before reading back any information into a buffer to make sure you are attempting to read-back the same number of bytes written.

Upvotes: 3

Related Questions