Linux 调用的设备驱动程序计数错误

Linux device driver called with wrong count

我在CentOS 7上实现了一个字符设备驱动,驱动在C程序中调用时运行正常,因此...

char bytes[8];
int fd = open("/dev/fortuna", O_RDONLY);
if (fd < 0) {
    perror("File open error: ");
    return -1;
}
int in = read(fd, bytes, 8);
if (in < 0) {
    perror("File read error: ");
}
close(fd);

调用驱动程序读取函数时计数 = 8,程序完成且没有错误。驱动函数原型为...

static ssize_t fortuna_read(struct file *filp, char *buff, size_t count, loff_t *offp);

但是,如果从 C++ 流调用读取,如下所示...

char bytes[8];
std::ifstream in("/dev/fortuna");
if (in.good()) {
    in.read(bytes, 8);
}
in.close();

调用驱动程序读取函数的次数为 8191。如果驱动程序是从 Java FileReader 调用的,如下所示...

File file = new File("/dev/fortuna");
file.setReadOnly();
FileReader reader = new FileReader(file);
char[] cbuf = new char[8];
int read = reader.read(cbuf);
reader.close();

调用驱动程序读取函数时计数 = 8192。写入函数的行为类似。

Google 让我失望了。有帮助吗?

这与缓冲有关。 我敢肯定,如果您一直在使用 stdio.h 和 fopen() I/O 系列而不是 open(),您会在 C 中看到同样的问题。

所以你应该禁用缓冲区。 对于 C++ 有这个答案: How to disable buffering on a stream?

感谢A.B,我也找到了Java解决方案。 FileReader 是一个缓冲 reader。正确的 Java class 是 FileInputStream.