I know how stdout buffer mode works,that is:
unbuffered: no buffer.
line buffered: flush the buffer when encounter a newline character.
block buffered: flush when the buffer is full.
I can understand the items above.
but I am confused about the stdin buffer works,I cannot imagine what will happen when use one of the three buffer mode.
And,for the three buffer mode,when does the stdin use which mode?
Thanks in advance.
// test02.c
int main(int argc, char *argv[]){
char ptr[20];
scanf("%s",ptr);
printf("%s\n",ptr);
return 0;
}
//./test02 < log
// in this case,scanf() just read the first line of log file
// can anyone explain how the stdin buffer works?
It is up to the implementation - how exactly is FILE I/O implemented - what do these modes do, also for stdout. It is nowhere guaranteed that setting line buffered will actually be line buffered.
When using glibc on linux when using normal files when underflowing read data to read
_IO_new_file_underflowis called here https://github.com/lattera/glibc/blob/895ef79e04a953cac1493863bcae29ad85657ee1/libio/fileops.c#L524_IO_SYSREAD (fp, fp->_IO_buf_base, fp->_IO_buf_end - fp->_IO_buf_base);. It does singlereadsyscall. You could follow setbuf to how it sets the buffer.However, practical answer is much more fun. Consider the following C program, that depending on the first argument, which is a number 1, 2 or 3, uses full-, line- or no buffering for stdin stream.
The following Makefile compiles the program and runs the program under strace with two lines of input using bash here string. It is so that we can see what
readsystem calls are being made:Make results in:
Setting
_IOFBFand_IOLBFjust does a singleread()with the size of the buffer10. These two work the same when reading. However,_IONBFdoes a single smallread(0, .., 1)up until a newline.