在我的内核模块中,我有以下读取功能:
static ssize_t sample_read(struct file *filp, char *buffer, size_t length, loff_t * offset) //read function here means to manage the communication with the button
{
int ret = 1;
int c;
c = gpio_get_value( BTN );
copy_to_user( buffer, &c, 1 ); //Buffer is the stack where to place the data read by function. copy_to_user copies the buffer on the user space. Here the reading is very simple. But if I would like to transfer more data?
printk( KERN_INFO "%s: %s read %d from BTN\n", module_name, __func__, c );
return( ret );
}
这里我通过缓冲区将c的值(即gpio的值)复制到用户空间。
如果我需要使用copy_to_user函数将更多数据复制到用户空间?
例如,如果我想复制到用户空间也是一个值int x = gpio_get_value(BTN_2)?
答案 0 :(得分:1)
首先,在sample_read()
更改
copy_to_user( buffer, &c, 1 );
到
copy_to_user( buffer, &c, sizeof(c));
因为要复制的第三个参数应该是number of bytes
,这应该是您要复制到用户空间的数据大小。
接下来,to copy more data
:使用结构。例如
typedef struct data {
int x;
int c;
} data_t;
data_t val;
val.x = gpio_get_value(BTN_2);
val.c = gpio_get_value(BTN);
copy_to_user( buffer, &val, sizeof(data_t));