Is the fread function blocking?

5.8k views Asked by At

I have the following code:

int buffer_max_size = 1024;
char* buffer = new char[buffer_max_size]
FILE* cout_file = fdopen(cout_pipe[0], "r");
while (fread( &buffer[0], sizeof(char),sizeof(char)*buffer_max_size, cout_file) != 0 )
{...}

cout_file is of type FILE* and is connected to a binary's stdout. That binary outputs some text on its std_out at 5 sec intervals.

It seems that fread is blocking until the cout_file contains buffer_max_size bytes.. Is that normal?

I would like to be able to read what is in the pipe right now without blocking.. Is that possible?

1

There are 1 answers

0
Ben Voigt On BEST ANSWER

If you want non-blocking I/O, use the OS's read and fcntl functions.

The <stdio.h> API (and also <fstream>) perform additional buffering and may automatically retry reads which end early (for example due to being interrupted by a signal), so they cannot be guaranteed to provide non-blocking I/O even if the underlying file descriptor is configured for it.

Not all OSes will use these POSIX names. In that case your options are platform-specific code (for example, on Windows you would be using ReadFile and SetNamedPipeHandleState), or using a wrapper library such as Boost ASIO to abstract the differences. But make sure that your wrapper is designed to expose non-blocking behavior, otherwise it will cause the same pain as <stdio.h>