Is fwrite non-blocking?

Before calling fflush can I read fwrite be = non-blocking? If not, why not, and what are my alternatives?

+6
c file-io
source share
3 answers

Technically, fwrite () is a blocking call because it does not return until the procedure completes. However, the completion definition for fwrite () is that the data you provided was written to the internal file buffer. As a side effect, part of this buffer can also be written to disk as part of the fwrite () call, but you cannot rely on this behavior. If you absolutely need the data to be on disk, you need to call fflush ().

+3
source share

fwrite() may be blocked. It uses (usually) an internal buffer with maximum length. It will send data (all or part of its internal buffer) when the buffer is full.

The setbuf() and setvbuf() functions allow you to change the maximum buffer length and actually provide a block for the buffer, but the details are implementation dependent, so you will have to read the documentation for your specific C library.

Conceptually, if you want a guaranteed non-blocking record under any conditions, then you will need potentially infinite buffers, which can be somewhat expensive. You can create your own functions for buffering data (in the RAM block, using realloc() so that it grows when necessary) and writing out (using fwrite() and possible fflush() ) only at the end. Alternatively, you can try using non-blocking I / O, in which the write functions are never blocked, but may respond that they refuse to accept your data due to internal overload. Non-blocking I / O is not part of the C standard itself (there is no f*() function for this, but it can be found under different names on some systems (for example, with fcntl() and write() on Unix systems).

+7
source share

fwrite () blocks. fwrite () can call fflush () internally at any time.

If all this is needed for buffering, then the buffers are in your own array. The fwrite buffer is usually a few K.

+2
source share

All Articles