Question

I'm talking to a process requiring user interaction using the following (PHP 5.3/ Ubuntu 12.04),

$pdes = array(
  0 => array('pipe', 'r'), //child's stdin
  1 => array('pipe', 'w'), //child's stdout
);
$process = proc_open($cmd, $pdes, $pipes);
sleep(1);
if(is_resource($process)){
  while($iter-->0){
    $r=array($pipes[1]);
    $w=array($pipes[0]);
    $e=array();
    if(0<($streams=stream_select($r,$w,$e,2))){
      if($streams){
        if($r){
          echo "reading\n";
          $rbuf.=fread($pipes[1],$rlen);  //reading rlen bytes from pipe
        }else{
          echo "writing\n";
          fwrite($pipes[0],$wbuf."\n");  //writing to pipe
          fflush($pipes[0]);
  }}}}
  fclose($pipes[0]);
  fclose($pipes[1]);
  echo "exitcode: ".proc_close($process)."\n";
}

And this is my test program in C,

#include <stdio.h>
int main(){
  char buf[512];
  printf("before input\n");
  scanf("%s",buf);
  printf("after input\n");
  return 0;
}

Now, the problem is $r is always empty after stream_select even if $pipes[1] is set to non-blocking where as write to $pipes[0] never blocks. However, things work fine without stream_select i.e. if I match reads and writes to the test program,

echo fread($pipes[1],$rlen);   //matching printf before input
fwrite($pipes[0],$wbuf."\n");  //matching scanf
fflush($pipes[0]);
echo fread($pipes[1],$rlen);   //matching printf after input

I couldn't figure out what's happening here. I'm trying to achieve something sort of web based terminal emulator here. Any suggestions on how to do this are welcome :)

Was it helpful?

Solution

Sorry guys for wasting your time. I figured out the problem a while later (sorry for the late update). Read was blocking due to a race condition.

I write to the process and immediately check the streams for availability. Write never blocks and data is not ready for reading yet (somehow even for 1 byte of data to be available it took 600ms). So, I was able to fix the problem by adding sleep(1) at the end of write block.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top