开发者

buffer confusion

Could anyone clarify on the types of buffers used by a program?

For eg:

I have a C program that reads from a stdin to stdout.

What are the buffers involved here? I'm aware that there are 2. One provided by the kernel on which a user don't have any control. One provided with standard streams n开发者_StackOverflowamely stdout, stdin and stderr. Each having a separate buffer.

Is my understanding correct?

Thanks, John


If you are working on linux/unix then you could more easily understand that there are three streams namely

1.STDIN: FILE DESCRIPTOR VALUE 0 (IN unix)

2.STDOUT :FILE DESCRIPTOR VALUE 1

3.STDERR :FILE DESCRIPTOR VALUE 2

By default these streams correspond to keyboard and monitor.In unix we can change these streams to read input from file instead of keyboard.To display output on a file rather than monitor using close(),dup() system calls.Yes there are 3 buffers involved.To clear the contents of input buffer in c we use fflush() function. If you want to know more about handling these streams in UNIX then let me Know.


The kernel (or other underlying system) could have any number of layers of buffering, depending on what device is being read from and the details of the kernel implementation; in some systems there is no buffering at that level, with the data being read directly into the userspace buffer.

The stdio library allocates a buffer for stdin; the size is implementation-dependent but you can control the size and even use your own buffer with setvbuf. It also allows you to control whether I/O is fully buffered (as much data is read into the buffer as is available), line buffered (data is is only read until a newline is encountered), or unbuffered. The default is line buffering if the system can determine that the input is a terminal, else fully buffered.

The story is similar for stdout. stderr is by default unbuffered.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜