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

时间:2016-12-28 10:05:13

标签: c linux-kernel linux-device-driver

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

读取功能永远不应String string = "Test, I am Adam"; // Anywhere in string b = string.indexOf("I am") > 0; // true if contains // Anywhere in string b = string.matches("(?i).*i am.*"); // true if contains but ignore case // Anywhere in string b = string.contains("AA") ; ,所以教师告诉我们使用return 0

我的问题是当我想在控制台中使用(用于exmaple)命令时尝试它:

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)

2 个答案:

答案 0 :(得分:1)

调用copy_to_user(buf,ringdev_buf,1)会导致从ringdev_buf到buf的1字节副本,所以正确,如果要将整个缓冲区复制到用户空间,则必须将其更改为copy_to_user(buf,ringdev_buf,ringdev_len)< / p>

答案 1 :(得分:0)

 if (copy_to_user(buf, ringdev_buf,ringdev_len)) 

应该是:

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

另外,我没有正确设置char设备。但是谢谢你的帮助:)。如果有人需要,我可以在循环缓冲区上发布我的写/读功能,每个思考都能正常工作。