2

我正在谈论一个需要使用以下(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";
}

这是我在 C 语言中的测试程序,

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

现在,即使将 if设置为 non-blocking where as write to never blocks ,问题$r始终是空的。但是,如果我没有匹配测试程序的读写,事情就可以正常工作,stream_select$pipes[1]$pipes[0]stream_select

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

我无法弄清楚这里发生了什么。我正在尝试在这里实现某种基于 Web 的终端仿真器。欢迎任何有关如何执行此操作的建议:)

4

1 回答 1

0

抱歉各位浪费了你们的时间。过了一会儿我发现了这个问题(抱歉更新晚了)。由于竞争条件,读取被阻塞。

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.

于 2012-09-29T08:18:11.347 回答