如何从仍在PHP中运行的进程获取部分输出?

I have a PHP script which runs a second script using proc_open().

The main script then passes the second script some data on STDIN.

I'd like the second script to be able to print output, and the main script to receive it.

So far that works fine.

However, my main script needs to call the second script many times, and to optimize this, I'd like to keep the resource open. That's ok too.

But I would see the output from the script progressively. That doesn't seem to be working: it looks like both scripts end up waiting for each other.

So what I want to do boils down to this:

// Main script
$resource = proc_open($command, $descriptorspec, $pipes);

foreach ($data as $line) {
  fwrite($pipes[0], $line);

  // Get output back from the second script's STDOUT to see how
  // it reacted to this piece of data.
  while ($line = fgets($this->pipes[1])) {
    dump("script: $line");
  }
}

// Second script.
while ($line = trim(fgets(STDIN))) {
  print "some sort of output to report how I'm doing";
}

I've figured out a way for the second script to tell the main script to stop waiting:

print " ";

and then the main script needs to do this when getting output from the process:

// Get output back from the second script's STDOUT to see how // it reacted to this piece of data. while ($line = trim(fgets($this->pipes[1]))) { dump("script: $line"); }

The second script is basically using an empty line as a message to the main script to say 'I'm doing outputting for now, stop listening'.