Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

c - Is fwrite non-blocking?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...