In the previous five chapters we walked through the steps of writing an simple charcater driver and for a virtual device and accessing it from the user space.
The limitation of driver written was it could not read using cat command . This was because the return value of the read function was not appropriate for the cat function.
The cat command continues to read from a file unless it is not informed that there is no further data to be read from the file, which is done by returning 0 when the end of file is reached.
To do this in our read function we have to keep count of the number of bytes that are written into the device. Hence we add a variable "written" into the write function which gets updated when data is written in to the device as follows
written = written + count ;
This value of written is assigned to another variable "read" every time device is opened. When the read function is called the variable "read" is compared with the variable "count", which indicates the number of bytes that the userspace wants to read. In case the count value is more than read, then we have to decrease the value of count to the amount of data present in the device i.e
if ( count > read)
count = read
And on every pass through the read function we keep decreasing the value of read by the count number of bytes that are read, and return the value of read.
Thus when end of file is reached the value of read becomes zero which when returned to cat, it would stop reading from the file.
Here is the drive code with the modified read and write functions. The steps to compile and insert the device are the same as in chapter-4
Assuming we have created a device by the name /dev/temp, we can communicate with the device as follows
$ echo "hi" > /dev/temp
$ cat /dev/temp
Or we can use the user application code as show in chapter-5