PREV INDEX NEXT

Author: Stan Eisenstat
Subject: Re: [Cs323] fflush follow up
Date: Monday, 07 Sep 2020, 09:09:10


    > Message Posted By: Unknown
    >
    > In a previous question, you responded "To ensure that the two outputs are
    > intermixed correctly, fiend must flush the buffer
    > for the FILE pointer stdout before it calls system() to
    > to execute the command."
    >
    > What does it mean to be "intermixed correctly." In the fflush page in MS
    > it says "causes all outstanding data on a file stream to be written
    > immediately" which I believe ensures that the file pointer has been
    > "committed", but I am not sure if these are related.

For the command

  % ./fiend . -print -exec echo {} \; > OUTPUT

you would expect the file OUTPUT to consist of successive pairs of lines that
contain the name of each file encountered.  The first line is written by fiend,
the second by the echo command.

The standard output of fiend is buffered.  Thus print statements write to a
buffer, and only when the buffer is full or fiend exits are the characters
written to OUTPUT.

The same is true for echo.  Thus when system() invokes bash to execute the echo
command, the characters are written to OUTPUT when echo exits.

Now consider what happens when fiend processes a file but does not flush the
buffer before calling system():

* -print adds the name of the file to the buffer, but only if the buffer is
  full is the name written to OUTPUT; and

* -exec causes echo to write the name of the file to OUTPUT immediately.

That is, the lines will not be intermixed.

WARNING:  The standard output is line-buffered when directed to a terminal
window, which means that the buffer is written whenever a newline is added.
Thus running the command above without the redirection to OUTPUT will give
the same result whether or not fiend calls flush() before calling system().

--Stan-
PREV INDEX NEXT