title: Is output read from popen()ed FILE* complete before pclose()?
body: <p><code>pclose()</code>'s man page says:</p>
  
  <blockquote>
    <p>The pclose() function waits for the associated process to terminate and returns the exit status of the command as returned by wait4(2).</p>
  </blockquote>
  
  <p>I feel like this means if the associated <code>FILE*</code> created by <code>popen()</code> was opened with type <code>"r"</code> in order to read the <code>command</code>'s output, then you're not really sure the output has completed until <em>after</em> the call to <code>pclose()</code>. But after <code>pclose()</code>, the closed <code>FILE*</code> must surely be invalid, so how can you ever be certain you've read the entire output of <code>command</code>?</p>
  
  <p>To illustrate my question by example, consider the following code:</p>
  
  <pre><code>// main.cpp
  
  #include &lt;iostream&gt;
  #include &lt;cstdio&gt;
  #include &lt;cerrno&gt;
  #include &lt;cstring&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  
  int main( int argc, char* argv[] )
  {
    FILE* fp = popen( "someExecutableThatTakesALongTime", "r" );
    if ( ! fp )
    {
      std::cout &lt;&lt; "popen failed: " &lt;&lt; errno &lt;&lt; " " &lt;&lt; strerror( errno )
                &lt;&lt; std::endl;
      return 1;
    }
  
    char buf[512] = { 0 };
    fread( buf, sizeof buf, 1, fp );
    std::cout &lt;&lt; buf &lt;&lt; std::endl;
  
    // If we're only certain the output-producing process has terminated after the
    // following pclose(), how do we know the content retrieved above with fread()
    // is complete?
    int r = pclose( fp );
  
    // But if we wait until after the above pclose(), fp is invalid, so
    // there's nowhere from which we could retrieve the command's output anymore,
    // right?
  
    std::cout &lt;&lt; "exit status: " &lt;&lt; WEXITSTATUS( r ) &lt;&lt; std::endl;
  
    return 0;
  }
  </code></pre>
  
  <p>My questions, as inline above: if we're only certain the output-producing child process has terminated after the <code>pclose()</code>, how do we know the content retrieved with the <code>fread()</code> is complete? But if we wait until after the <code>pclose()</code>, <code>fp</code> is invalid, so there's nowhere from which we could retrieve the command's output anymore, right?</p>
  
  <p>This feels like a chicken-and-egg problem, but I've seen code similar to the above all over, so I'm probably misunderstanding something. I'm grateful for an explanation on this.</p>