如何使用调用copy_from_user正确的方法是什么? [英] how is the correct way to use copy_from_user?

查看:3296
本文介绍了如何使用调用copy_from_user正确的方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将一个数值从用户空间复制到内核函数空间:

I am trying to copy a value from user space to kernel space with the function:

static ssize_t device_write(struct file *filp, const char *buff, size_t len, loff_t  *off) 
{

    unsigned long copy=0;
    int desp=0; 

    copy = copy_from_user(&desp, &len, 4);  

    printk(KERN_ALERT "copy: %lx\n", copy);      
    printk(KERN_ALERT "desp: %d\n", desp);
}

,其中LEN是存在于用户空间的变量,我想复制它在内核空间DESP

where "len" is the variable that exists in the user space, and I want to copy it to "desp" in the kernel space

函数调用我从用户空间提出的是(写是device_write根据的file_operations结构):

the function call I make from the user space is (write is device_write according to file_operations struct):

 write (fd,buffer,8, &off);

当我打印应当被存储在DESP的值始终为0(应为8)。
什么是我的code中的问题?我已经看到了几个例子,我实施了许多变化,但没有工作。

when I print the value that should be stored in "desp" is always 0 (should be 8). What is the problem in my code? I've been seeing several examples and I implemented many variations but none works.

推荐答案

函数原型的手册是:

ssize_t供写入(INT FD,常量无效* buf中,为size_t计数);

所以,你只需要通过3值,即:文件描述符 FD 缓存,其中数据的所在,计数要写入的字节。

So you only need to pass 3 values to write, namely: the file descriptor fd, buffer where your data lies, and count of bytes you want to write.

这对于用户空间。现在让我们转移到内核空间写功能,即你的 device_write

This regarding the user space. Now let's move to the kernel space write function, i.e. your device_write.

这个函数的参数 BUF 是其中一个包含你想从用户空间写数据,计数是发送到由内核写入的数据的长度。所以,你应该将数据从 BUF 复制指针,而不是 LEN

The argument buf to this function is the one which contains data which you want to write from user space, count is the length of data sent to be written by the kernel. So you are supposed to copy data from buf pointer and not len.

因此​​,正确的方法是:

So, the correct way would be:

char *desp;  //allocate memory for this in kernel using malloc
copy_from_user (desp, buff, len);

这应该做的。

这篇关于如何使用调用copy_from_user正确的方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆