gpt4 book ai didi

c - Linux 内核 write() 和 read() 函数

转载 作者:行者123 更新时间:2023-11-30 15:01:33 25 4
gpt4 key购买 nike

您好,我的学校代码需要一些帮助。

读取函数不应该返回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) 中将任何值放入 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;
}

最佳答案

调用copy_to_user(buf,ringdev_buf,1)会导致从ringdev_buf到buf的1字节复制,所以它是正确的,如果你想将整个缓冲区复制到用户空间,你必须将其更改为copy_to_user(buf,ringdev_buf,ringdev_len)

关于c - Linux 内核 write() 和 read() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41359672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com