Linux Device Driver Programming Lecture 43- Write method implementation

 

Write method implementation

 

 

In this article, let’s implement the write method. I will use the same lines of code from the read method. Copy all codes from the read method and change that, as shown below.

ssize_t pcd_write(struct file *filp, const char __user *buff, size_t count, loff_t *f_pos)
{
       pr_info("Write requested for %zu bytes\n",count);
       pr_info("Current file position = %lld\n",*f_pos);


       /* Adjust the 'count' */
       if((*f_pos + count) > DEV_MEM_SIZE)
           count = DEV_MEM_SIZE - *f_pos;

       if(!count){
           return -ENOMEM;

       /*copy from user */
       if(copy_from_user(device_buffer[*f_pos],buff,count)){
            return -EFAULT;
}

       /*update the current file postion */
       *f_pos += count;

       pr_info("Number of bytes successfully written = %zu\n",count);
       pr_info("Updated file position = %lld\n",*f_pos);

       /*Return number of bytes which have been successfully written */
       return count;
}

Write method

The first line is, let’s modify this as write requested. The next print statement is, current file position, keep this line as it is. And then you have to adjust the count here, this code will remain the same.

Instead of copy_to_user, you have to use copy_from_user.  So, the first one is the destination. Destination, in our case, is our device_buffer. And the second argument is the source. That is buffer, user buffer after that count. That seems to be correct. And after that, update the current file position. So, the number of bytes successfully written.

The next statement is to print, update a  file position that will remain the same, and return the number of bytes which have been successfully return. Return count.

Here above copy_from_user, we need to add if count is 0, you should return ENOMEM. If not of count, then return ENOMEM. 

 

For copy_to_user  and copy_from_user, we have to use the appropriate header file, and the header file is linux/uaccess.h. And you have to write the address of device_buffer. This has to be the address of device_buffer.  Save and exit.

Figure 2. Address of operator
Figure 1. Address of operator

 

Build it. Everything is fine.

Figure 3. Make host
Figure 2. Make host

 

And in the next article, let’s finish our other methods. I will see you in the next article.

 

FastBit Embedded Brain Academy Courses,

Click here:  https://fastbitlab.com/course1

 

FastBitLab

The FastBit Embedded Brain Academy uses the power of internet to bring the online courses related to the field of embedded system programming, Real time operating system, Embedded Linux systems, etc at your finger tip with very low cost. Backed with strong experience of industry, we have produced lots of courses with the customer enrolment over 3000+ across 100+ countries.