title: Read from popen(3) in realtime
body: <p>Basically, I want to store entire program output in buffers for longer runtimes. Issue is, <code>popen(3)</code> forks a process and since data to be read by <code>poll(2)</code> is delivered in buffered blocks, any intermittent lines between each subsequent call of <code>poll(2)</code> may result in output being skipped in the child process. I was hoping blocking with poll(2) would temporarily halt the forked process, but this is not the case. Is there some way to gain control of this forked process that would allow it to pause, read input, pause, read input, ...? I don't see any way of dropping <code>popen(3)</code>, but it looks like <code>poll(2)</code> should be replaced.</p>
  <p><strong>/tmp/script.sh</strong></p>
  <pre><code>#!/bin/bash
  
  for i in {1..5}
  do
      echo $i
      sleep 1
  done
  </code></pre>
  <p><strong>main.c</strong></p>
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;poll.h&gt;
  
  #define OUT_LEN 256
  #define CMD_LEN 128
  
  void die(char *msg)
  {
      printf(&quot;Error: %s\n&quot;, msg);
      exit(EXIT_FAILURE);
  }
  
  int main()
  {
      FILE *fp;
      char cmd[CMD_LEN+1] = &quot;/tmp/script.sh&quot;;
      char output[OUT_LEN+1];
      struct pollfd *ps;
      int n = 1, c, x;
  
      if((fp = popen(cmd, &quot;r&quot;)) == NULL)
          die(&quot;failed in popen()&quot;);
  
      output[OUT_LEN] = '\0';
      ps = calloc(n, sizeof(struct pollfd));
      ps[0].fd = fp-&gt;_fileno;
      ps[0].events = POLLIN;
  
      for(x = 0; (c = fgetc(fp)) != EOF &amp;&amp; x &lt; OUT_LEN; ++x)
      {   
          if(poll(ps, n, 0) == -1) { die(&quot;poll()&quot;); }
          if(ps[0].revents &amp; POLLIN)
              output[x] = c;
      }   
      if(x &gt;= OUT_LEN)
          die(&quot;LEN too short for stdout of cmd&quot;);
  
      printf(&quot;see output below:\n%s&quot;, output);
  
      return 0;
  }
  </code></pre>
  <p><strong>Desired output:</strong></p>
  <pre><code>see output below:
  1
  2
  3
  4
  5
  </code></pre>
  <p><strong>Actual output:</strong></p>
  <pre><code>see output below:
  </code></pre>