2017-03-21 64 views
0

我試圖在Linux驅動程序中實現char設備驅動程序。當我嘗試向我的驅動程序中回顯字符串時,結果非常奇怪。來自char設備模塊的linux內核中的Dmesg輸出

我的代碼來存儲字符串我輸入:

int max_size = 1; 
char store[1] = {0}; 
char message[100] = {0}; 
ssize_t hello_write(struct *filep, const char *buffer, size_t length, loff_t *position) 

{ 
    if(length> max_size) 
    length = max_size; 
    if(copy_from_user(message, buffer, length)) 
    return -EFAULT; 
    strncpy(store, message, max_size); 
    printk(KERN_INFO "Actually stored in kernel:%s", store); 
    return max_size; 
} 
ssize_t hello_read(struct file *filep, char *buffer, size_t length, loff_t *postion) 
{ 
    int error_count = 0; 
    error_count = copy_to_user(buffer, store, max_size); 
    if(error==0){ 
    printk(KERN_INFO "read message from kernel: %s", store); 
    return 0; 
    } 
    else{ 
    printk(KERN_INFO "failed to send %d chars to user", error_count); 
    return -EFAULT; 
    } 
} 

測試:

echo ginger > /dev/test 
cat /dev/test 

我打算只存儲每個輸入字符串的第一個字母,任何與功能strncpy?通過系統調用write返回

store the string one by one

回答

2

值被解釋爲數處理字節。

echo調用系統調用write()反覆直到它處理所有輸入字節其他標準的輸出工具。

因此,當您只需要存儲輸入的單個字節時,您需要返回輸入的全長以將其標記爲已處理。

更正確實施.write是:

ssize_t hello_write(struct *filep, const char * __user buffer, size_t length, loff_t *position) 
{ 
    if((*position == 0) && (length > 0)) { 
    // Store the first byte of the first input string. 
    if(copy_from_user(message, buffer, 1)) 
     return -EFAULT; 
    strncpy(store, message, 1); 
    } 
    printk(KERN_INFO "Actually stored in kernel:%s", store); 
    // But mark the whole string as processed 
    *position += length; 
    return length; 
} 
+0

感謝什麼樣的建議,我才意識到自己忘了重新定位指針。現在它工作得很好。再次感謝! – Ethan