如何copy_to_user一个字符串并在Linux内核读取函数中使用offp

时间:2014-01-09 21:57:41

标签: c linux linux-kernel kernel device

宣称:

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

并实施了read功能:

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;
}
  • 如何考虑offp
  • 目前它将status无限地打印到屏幕

3 个答案:

答案 0 :(得分:3)

感谢大家的评论,我想出了以下实现,我认为这是使用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;
}

答案 1 :(得分:1)

在函数返回“0”或错误之前,read_proc()不会停止读取。我相信你需要修改你的read_proc才能拥有这个逻辑。

答案 2 :(得分:1)

要了解read的返回值,请让我引用Linux Device Drivers 3rd edition

The return value for read is interpreted by the calling application program:

    If the value equals the count argument passed to the read system call, the requested number of bytes has been transferred. This is the optimal case.

    If the value is positive, but smaller than count, only part of the data has been transferred. This may happen for a number of reasons, depending on the device. Most often, the application program retries the read. For instance, if you read using the fread function, the library function reissues the system call until completion of the requested data transfer.

    If the value is 0, end-of-file was reached (and no data was read).

    A negative value means there was an error. The value specifies what the error was, according to <linux/errno.h>. Typical values returned on error include -EINTR (interrupted system call) or -EFAULT (bad address).

因此,总之,您需要始终更新offp并在开始阅读之前检查它的值,如果已经传递了数据长度,则需要return 0,如果部分读取,则返回数量读取的字节数,在这种情况下你将更新offp所以如果传递了数据长度,下次调用read将返回0。

static ssize_t read_proc(struct file *filep, char __user *buf,
                size_t len, loff_t *offp)
{
    size_t count = len, status_length = strlen(status);
    ssize_t retval = 0;
    unsigned long ret = 0;

    if (*offp >= status_length)
        goto out;
    if (*offp + len > status_length)
        count = status_length - *offp;

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

out:
    return retval;
}

参考文献: