2

I have implemented a character device driver on CentOS 7. The driver is functioning normally when it is called from a C program, thusly...

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);

The driver read function is invoked with count = 8 and the program completes with no errors. The driver function prototype is...

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

However, if the read is invoked from a C++ stream, as follows...

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

The driver read function is invoked with count = 8191. If the driver is invoked from a Java FileReader, as follows...

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();

The driver read function is invoked with count = 8192. The write functions behave similarly.

Google has failed me. Help?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
SteveB
  • 483
  • 1
  • 4
  • 18

2 Answers2

2

It has to do with buffering. I'm quite sure if you had been using stdio.h and the fopen() I/O family instead of open(), you'd have seen the same problem in C.

So you should disable buffers. For C++ there's this answer: How to disable buffering on a stream?

A.B
  • 376
  • 4
  • 11
1

Thanks to A.B, I also found the Java solution. FileReader is a buffered reader. The correct Java class to use is FileInputStream.

SteveB
  • 483
  • 1
  • 4
  • 18