Home > Mobile >  Effect of setvbuf function with null parameters
Effect of setvbuf function with null parameters

Time:11-24

At the very beginning of a C program, I encountered the following line:

setvbuf(stdout, NULL, _IONBF, 0);

As I didn't know this setvbuffunction, I checked its documentation here. However, after this line, in the Parameters/mode section:

_IONBF No buffering: No buffer is used. Each I/O operation is written as soon as possible. In this case, the buffer and size parameters are ignored.

I remain confused. If this mode makes half of the parameters ignored, what exactly did this line bring to the program ?

CodePudding user response:

setvbuf(stdout, NULL, _IONBF, 0); requests that the stream not use any buffering. Specifically, in the third parameter, _IONBF requests no buffering. For a stream that is buffered, this call requests a change to make it unbuffered.

Since there is no buffer, the stream does not need a buffer (passed in the second parameter) or a length for the buffer (passed in the fourth parameter).

If the third parameter is _IOLBF or _IOFBF, the call requests buffering (line buffering or full buffering, respectively), and then the second and fourth parameters are used. (They may still be NULL and 0 to request that setvbuf allocate the memory, or they may have other values to provide a buffer arranged by the caller.)

CodePudding user response:

I remain confused. If this mode makes half of the parameters ignored, what exactly did this line bring to the program ?

Buffered I/O operation first place the data into the buffer, then when sone conditions are met (for example special case data - like '\n' for stdout, buffer size reaches a particular threshold, special function is called (the buffer flushed) etc) the data from the buffer is being sent.

If you disable the buffer the data is not placed into the buffer only directly send. It very handy in many circumstances for example when more than one thread is sending the data and only one buffer is used you may get mixed data from both.

  • Related