2014-12-30 82 views
0

以我內核模塊我有以下讀取功能:copy_to_user:處理多個數據

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

你說的'複製到用戶空間更data'和'複製到用戶空間也值爲INT X = gpio_get_value(BTN_2)?'是什麼意思? –

+0

您可以從sysfs中導出設備信息/值,而不是使用結構。 – askb

+0

嗨askb ...我不知道如何使用sysfs。你可以做一個例子或一個小的解釋? – Anth

回答

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)); 
+0

對不起。我知道緩衝區是一個char *,所以當我在用戶空間時,如何獲取用戶空間中的兩個值?同樣在用戶空間中,我應該通過typedef來創建data_t類型來獲取這兩個值? – Anth

+0

在用戶空間中,將'typecast char *'轉換爲'data_t',然後讀取值 –