【发布时间】:2018-05-02 08:08:36
【问题描述】:
我一直在编写一个可以从用户空间读取和写入的内核空间设备驱动程序。打开、读取、释放操作都可以完美运行。我遇到的问题是应该访问设备驱动程序并向其写入内容的用户空间代码。
用户空间程序写入两个文件:1) 到 .txt 文件(并在控制台打印 a 以让用户知道它已完成),以及 2) 到设备驱动程序(并且还打印文本让用户知道它也已完成)。
下面是完整的用户空间代码:
int main() {
FILE *fp;
fp = fopen("./test.txt","w");
fputs("Test\n", fp);
fclose(fp);
printf("Printed to txt\n"); //Prints normally.
fp = fopen("/dev/testchar", "w");
fputs("Test\n", fp);
fclose(fp);
printf("Printed to dev\n"); //Never gets to this point
return 0;
}
当我编译并运行代码时,程序会吐出
Printed to txt
然后一直挂起,直到调用 ctrl+c。它永远不会超过第二个fputs()。
在监视 kern.log 时,我看到无休止地调用写入设备驱动程序。
这里我从设备驱动中提取了相关代码:
static char msg[256] = {0};
static struct file_operations fops =
{
.write = dev_write
};
static ssize_t dev_write(struct file *file, const char *buf, size_t len, loff_t *ppos)
{
sprintf(msg, "Input:%s, Chars:%lu\n", buf, len);
printk(KERN_NOTICE "%s\n", msg);
return 0;
}
uname -r: 4.10.0-38-generic
gcc -v: gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.4)
我的问题是:为什么程序在写入设备时会陷入无限循环,我该如何解决?
提前致谢。任何帮助将不胜感激。
【问题讨论】:
-
不确定这个。你不需要处理关闭操作吗?看看linux.die.net/lkmpg/x892.html
.release.writefile_operations Fops
标签: c linux kernel driver device