开发者

Is fwrite non-blocking?

开发者 https://www.devze.com 2022-12-23 14:22 出处:网络
Before calling fflush can I consider fwrite to be = a non-blocking write? If开发者_开发技巧 not, why not and what are my alternatives?fwrite() may block. It uses (usually) an internal buffer with a ma

Before calling fflush can I consider fwrite to be = a non-blocking write? If开发者_开发技巧 not, why not and what are my alternatives?


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

The setbuf() and setvbuf() functions let you alter the buffer maximum length, and actually provide the 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 guaranteed non-blocking writes under all conditions, then you need potentially infinite buffers, which can be somewhat expensive. You could make your own functions for buffering data (within a block of RAM, using realloc() to make it grow when necessary) and write out (with fwrite() and possible fflush()) only at the end. Alternatively, you could try to use non-blocking I/O in which write functions never block but may respond that they refuse to accept your data due to internal congestion. Non-blocking I/O is not part of the C standard itself (there is no f*() function for that) but can be found under various names on some systems (e.g. with fcntl() and write() on Unix systems).


Technically fwrite() is a blocking call in that it does not return until the procedure has completed. However the definition of completion for fwrite() is that the data you supply has been written to an internal file buffer. As a side effect some of that buffer may also be written to the disk as part of the fwrite() call but you cannot rely on that behavior. If you absolutely require the data to be on the disk you need to call fflush().


fwrite() is blocking. fwrite() may call fflush() internally at any time.

If all you need it to buffer, then buffer in your own array. fwrite's buffer is typically a few K.

0

精彩评论

暂无评论...
验证码 换一张
取 消