你好,我需要一些幫助,我的代碼爲學校。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;
}
閱讀應該複製給用戶整個要讀取的緩衝區,而不只是一個字符。當你等待等待後情況仍然不滿意時,請小心;在這種情況下,你應該返回-EINTR。在寫作方面,事情實際上看起來很好 –
我們還希望1234 \ n5 \ n是echo命令後面的內容(cat會在單獨的行中顯示1234和5) –
@PaulStelian發佈一個答案:p。 – Stargateur