2016-12-28 152 views
0

你好,我需要一些幫助,我的代碼爲學校。Linux內核寫入()和讀取()函數

閱讀功能永遠不應該return 0所以老師告訴我們使用wait_event_interruptible

我的問題是,當我想嘗試使用(對於〔實施例)在控制檯命令:

echo 1234 > ringdev # my character device 
echo 5 > ringdev 
cat ringdev 

我只得到一個結果:5

我希望得到一個結果:

1234 5

全局變量:

static char ringdev_buf[4096]; 
static size_t ringdev_len; 

讀取功能:

static ssize_t ringdev_read(struct file *filp, char __user *buf, size_t count, 
     loff_t *off) 
{  
    ssize_t ret = 0; 
    while(1) { 
     wait_event_interruptible(head,ringdev_len!=0); 
     mutex_lock(&ringdev_lock); 
     if(ringdev_len!=0) { 
      ret = -EFAULT; 
      if (copy_to_user(buf, ringdev_buf,ringdev_len)) { // I was trying everything in the ringdev_len position. 
       ret = ringdev_len; 
       goto out_unlock; 
      } 
     } 
     mutex_unlock(&ringdev_lock); 
    } 
    out_unlock: 
    mutex_unlock(&ringdev_lock); 
    return ret; 
} 

我試圖把任何值計數功能copy_to_user(buf, ringdev_buf,count)但結果總是相同的。

static ssize_t ringdev_write(struct file *filp, const char __user *buf, 
     size_t count, loff_t *off) 
{ 
    ssize_t ret=0; 
    mutex_lock(&ringdev_lock); 
    ret=-EFAULT; 
    if(ringdev_len + count < sizeof(ringdev_buf)) { 
     if (copy_from_user(ringdev_buf+ringdev_len, buf, count)==0) { 
      ringdev_len=ringdev_len+count; 
      ret=count; 
      wake_up_interruptible(&head); 
      goto out_unlock; 
     } 
    } else { 
     ret=-ENOSPC; 
    } 
    out_unlock: 
    mutex_unlock(&ringdev_lock); 
    return ret; 
} 
+0

閱讀應該複製給用戶整個要讀取的緩衝區,而不只是一個字符。當你等待等待後情況仍然不滿意時,請小心;在這種情況下,你應該返回-EINTR。在寫作方面,事情實際上看起來很好 –

+0

我們還希望1234 \ n5 \ n是echo命令後面的內容(cat會在單獨​​的行中顯示1234和5) –

+0

@PaulStelian發佈一個答案:p。 – Stargateur

回答

1

呼叫copy_to_user的(BUF,ringdev_buf,1)導致從ringdev_buf到緩衝區,1個字節的副本,所以它的吧,如果你想複製整個緩衝區到用戶空間,則必須將其更改爲copy_to_user(BUF,ringdev_buf ,ringdev_len)

+0

我已經改變了它,但我仍然得到: – Akihito

+0

我已經改變它,但我仍然只得到最後的回聲響應 – Akihito

+0

它應該是opy_to_user(buf,ringdev_buf,ringdev_len)而不是opy_to_user(buf,ringdev_buf,4096) –

0
if (copy_to_user(buf, ringdev_buf,ringdev_len)) 

應該是:

if (copy_to_user(buf, ringdev_buf,ringdev_len)==0) 

另外,我沒有正確地使字符設備。但謝謝你的幫助:)。如果有人需要,我可以在這裏發佈我的寫/讀函數在循環緩衝區,每個想法都能正常工作。