简体   繁体   中英

Disable buffering for stdin and stdout using setvbuf()

When I was reading about the usage of setvbuf() , I came across the _IONBF (no buffering) mode. So I was curious how stdin and stdout will be affected if I try to disable the buffering. Below is an example code :

#include <stdio.h>

int main(void)
{

   int num;
   char a;
   setvbuf(stdin, NULL, _IONBF, 0); //turn off buffering
   scanf("%d", &num);
   a = getchar();
   printf("%d %c\n", num , a);

       return 0;
}

1.) From the above code, the sample input I've given to the program ( 123a and etc) yield the same output even if I didn't include setvbuf() .

2.) I understand that buffer is an intermediate storage in which a chunk of data can be filled into it and all those data will be send to the input or output stream either when the buffer is full or a newline is given.

3.)So what does the effect of disabling buffer? Is it in terms of performance?

It is partly performance and partly control over how stream library functions (fread, fgets, fprintf, etc.) relate to actual I/O to a device/file.

For example, stream output to a character device (eg your terminal) are, by default, line buffered. The effect of this is that the following code,

printf("start ");
sleep(10);
printf("stop\n");

will wait 10 seconds and then print start stop [NL]. The first print was buffered because there was no new-line to flush the buffer. To get start to print, then sleep 10 seconds,you could either add a fflush call before the sleep call, or turn off buffering on stdout with setvbuf .

Stream output to a block device or disk file is, by default, fully buffered. This means that the buffer won't flush until either you overflow the buffer or do an fflush . This could be a problem with files, for example, if you want to monitor the output in real-time with tail -f . If you know that this monitoring may be done, you could switch the stream to line-buffering so that every time a new-line is printed, the buffer is flushed to the file. This would be at the cost of increased overhead as disk blocks are written several times as new-lines are printed. (Note: this overhead depends on how the file system is mounted. A fixed drive, mounted write-back cache, will have less overhead as the OS buffers writes to the disk, vs. a removable drive mounted write-though. In the latter case, the OS will try to do the partial writes to improve the chances of avoiding data loss if the drive is removed without dismounting.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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