Advanced Programming in the UNIX® Environment

(lily) #1
ptg10805159

Section 5.4 Buffering 145


5.3 StandardInput, StandardOutput, and StandardError


Three streams arepredefined and automatically available to a process: standardinput,
standardoutput, and standarderror.These streams refer to the same files as the file
descriptors STDIN_FILENO, STDOUT_FILENO,and STDERR_FILENO,respectively,
which we mentioned in Section 3.2.
These three standardI/O streams arereferenced through the predefined file
pointersstdin,stdout,andstderr.The file pointers aredefined in the<stdio.h>
header.

5.4 Buffer ing


The goal of the buffering provided by the standardI/O library is to use the minimum
number ofreadandwritecalls. (Recall Figure3.6, which showed the amount of CPU
time required to perform I/O using various buffer sizes.) Also, this library tries to do
its buffering automatically for each I/O stream, obviating the need for the application to
worry about it. Unfortunately,the single aspect of the standardI/O library that
generates the most confusion is its buffering.
Three types of buffering areprovided:


  1. Fully buffered. In this case, actual I/O takes place when the standardI/O
    buffer is filled. Files residing on disk arenormally fully buffered by the
    standardI/O library.The buffer used is usually obtained by one of the standard
    I/O functions callingmalloc(Section 7.8) the first time I/O is performed on a
    stream.
    The termflushdescribes the writing of a standardI/O buffer.Abuffer can be
    flushed automatically by the standardI/O routines, such as when a buffer fills,
    or we can call the functionfflushto flush a stream. Unfortunately, in the
    UNIX environment,flushmeans two different things. In terms of the standard
    I/O library,itmeans writing out the contents of a buffer,which may be partially
    filled. In terms of the terminal driver,such as the tcflush function in
    Chapter 18, it means to discardthe data that’s already stored in a buffer.

  2. Line buffered. In this case, the standardI/O library performs I/O when a
    newline character is encountered on input or output. This allows us to output a
    single character at a time (with the standardI/Ofputcfunction), knowing that
    actual I/O will take place only when we finish writing each line. Line buffering
    is typically used on a stream when it refers to a terminal—standardinput and
    standardoutput, for example.
    Line buffering comes with two caveats. First, the size of the buffer that the
    standardI/O library uses to collect each line is fixed, so I/O might take place if
    we fill this buffer beforewriting a newline. Second, whenever input is
    requested through the standardI/O library from either (a) an unbuffered stream

Free download pdf