2016-11-22 119 views
2

我正在爲加速度計實現SPI驅動程序。 SPI部分已完成,但無法讀取用戶空間的值。無法從linux字符設備讀取

static char charDevMessage[CD_BUFFER_SIZE] = { 0 }; 
... 
static ssize_t char_dev_read(struct file *filep, char *buffer, size_t len, loff_t *position) 
{ 

    int error_count = 0; 
    struct xyz_values xyz; 
    size_t size_requested; 

    xyz = adxl345_get_xyz(); 
    memset(charDevMessage, 0, CD_BUFFER_SIZE); 
    sprintf(charDevMessage, "%d,%d,%d", xyz.x, xyz.y, xyz.z); 
    printk(KERN_INFO "MOB: %s, requested size: %d\n", charDevMessage, len); 

    if (len >= CD_BUFFER_SIZE) 
    { 
     size_requested = CD_BUFFER_SIZE; 
    } 
    else 
    { 
     size_requested = len; 
    } 

    error_count = copy_to_user(buffer, charDevMessage, size_requested);  

    if (error_count == 0)   
    { 
     printk(KERN_INFO "MOB: Sent %d characters to the user\n", size_requested); 
     return (size_requested = 0);  

    } 
    else 
    { 
     printk(KERN_INFO "MOB: Failed to send %d characters to the user\n", error_count); 
     return -EFAULT;    

    } 
} 

節點在安裝驅動程序時已創建。但是,當我嘗試cat或試圖通過python讀取它返回一個空字符串。

dmesg說,它已發送成功用戶空間:

[ 3094.495972] MOB: SPI Character device has been opened 1 time(s) 
[ 3094.506075] MOB: -349,-512,511 , requested size:49 
[ 3094.514487] MOB: Sent 256 characters to the user 
[ 3094.522646] MOB: Character device successfully closed 
[ 3120.658568] MOB: SPI Character device has been opened 2 time(s) 
[ 3120.668609] MOB: 0,0,0 , requested size:48 
[ 3120.676392] MOB: Sent 256 characters to the user 
[ 3120.684740] MOB: Character device successfully closed 

我在做什麼錯?

+3

'return(size_requested = 0);'返回0,返回0表示文件結束。 – immibis

+0

那麼它會關閉內核端的文件? – obayhan

+0

您的第一個printk格式錯誤。 –

回答

2

您misaunderstood的.read函數的概念:

讀者(用戶空間)只能看到值由.read返回並把它解釋爲數量已經讀取字節。

至於最後一個參數.readposition你的情況),其解釋完全處於駕駛員的作者。值爲position,由內核核心在文件打開時被初始化爲0。之後,內核本身從不修改它。

如果你想永遠從一開始讀,你可能只是忽略position參數:

return size_requested; 

或者語義上更好,你可以增加值,由position指出,所以它會反映讀取的字節數。但否則忽略它:

*position += size_requested; 
return size_requested; 
+0

哦,我的錯誤。我明白了你現在告訴你的觀點。感謝您的努力(:那麼零意味着什麼閱讀和負值意味着錯誤照常權 – obayhan

+1

沒有,零表示EOF,這是不一樣的*不讀*否則肯定的,負面返回代碼,用戶空間將得到? '-1'讀取,'errno'將被設置爲返回碼,不同之處在於它是正的。 –

+0

哦,好的。謝謝 – obayhan