Tuesday, February 22, 2022

[SOLVED] How to copy_to_user a string and use offp in a Linux Kernel read function

Issue

Declared:

static char status[128] = "off\0";

and implemented a read function:

static ssize_t read_proc(struct file *filep, char __user *buf,
                    size_t len, loff_t *offp)
{
    ssize_t cnt = strlen(status), ret;

    ret = copy_to_user(buf, status, cnt);
    *offp += cnt;
    return cnt;
}
  • How do I take into account the offp?
  • currently it prints endless the status to screen

Solution

Thanks the guys comments here I came up with the following implementation, which I believe is the right way to use offp:

static ssize_t read_proc(struct file *filep, char __user *buf,
                    size_t len, loff_t *offp)
{

    ssize_t cnt = strlen(status), ret;

    /* ret contains the amount of chare wasn't successfully written to `buf` */
    ret = copy_to_user(buf, status, cnt);
    *offp += cnt - ret;

    /* Making sure there are no left bytes of data to send user */
    if (*offp > cnt)
         return 0;
    else
         return cnt;
}


Answered By - 0x90
Answer Checked By - Terry (WPSolving Volunteer)