title: How to read stdout from a subprocess when the latter does not flush its stdout?
body: <p>Before the below code I do:</p>
  
  <ul>
  <li><p>create 1 pipe to read output from forked process</p></li>
  <li><p>fork()</p></li>
  <li><p>execv() a python script</p></li>
  </ul>
  
  <p>Then in the parent process I do:</p>
  
  <pre><code>//set pipes to non-Blocking
  File * cout_f = fdopen(cout_pipe[0], "r");
  int flags = fcntl(cout_pipe[0], F_GETFL, 0);
  fcntl(cout_pipe[0], F_SETFL, flags|O_NONBLOCK);
  
  // read from pipe and send it up through a callback method
  int stat;
  size_t size = 0;
  char buffer [ 1000 ];
  do
  {
      while((size = fread(buffer, sizeof(char), sizeof(char)*1000, cout_f))!=0)
      {
          call_back_function(buffer, size);
      }
  }while(waitpid(child_pid, &amp;stat, WNOHANG) != -1)
  
  //Do 1 extra read
  while((size = fread(buffer, sizeof(char), sizeof(char)*1000, cout_f))!=0)
  {
      call_back_function(buffer, size);
  }
  </code></pre>
  
  <p>The problem I am facing happens when the child process prints to stdout and exits (normally) before flushing. I miss what was sent in the pipe.</p>
  
  <p>Here are my questions:</p>
  
  <ul>
  <li>Is the above code safe/correct or can it be improved?</li>
  <li>Is there a way to read the entire pipe at the last moment when the subprocess dies, even if it doesn't flush its stdout?</li>
  </ul>