简体   繁体   English

setvbuf function 与 null 参数的效果

[英]Effect of setvbuf function with null parameters

At the very beginning of a C program, I encountered the following line:在 C 程序的最开始,我遇到了以下行:

setvbuf(stdout, NULL, _IONBF, 0);

As I didn't know this setvbuf function, I checked its documentation here .因为我不知道这个setvbuf function,所以我在这里查看了它的文档。 However, after this line, in the Parameters/mode section:但是,在这一行之后,在参数/模式部分:

_IONBF No buffering: No buffer is used. _IONBF无缓冲:不使用缓冲。 Each I/O operation is written as soon as possible.每个 I/O 操作都尽可能快地写入。 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?如果这种模式使一半的参数被忽略,那么这一行究竟给程序带来了什么?

setvbuf(stdout, NULL, _IONBF, 0); requests that the stream not use any buffering.要求 stream 不使用任何缓冲。 Specifically, in the third parameter, _IONBF requests no buffering.具体来说,在第三个参数中, _IONBF请求不进行缓冲。 For a stream that is buffered, this call requests a change to make it unbuffered.对于缓冲的 stream,此调用请求更改以使其无缓冲。

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).由于没有缓冲区,stream 不需要缓冲区(在第二个参数中传递)或缓冲区的长度(在第四个参数中传递)。

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.如果第三个参数是_IOLBF_IOFBF ,则调用请求缓冲(分别为行缓冲或全缓冲),然后使用第二个和第四个参数。 (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.) (它们可能仍然是NULL和 0 以请求setvbuf分配 memory,或者它们可能具有其他值以提供由调用者安排的缓冲区。)

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.缓冲 I/O 操作首先将数据放入缓冲区,然后当满足某些条件时(例如特殊情况数据 - 如标准输出'\n' ,缓冲区大小达到特定阈值,调用特殊 function(缓冲区刷新)等)正在发送缓冲区中的数据。

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.在许多情况下它非常方便,例如当多个线程发送数据并且只使用一个缓冲区时,您可能会从两者中获得混合数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM