php proc_open 读取子进程的数据
<?php
/*
 * 读取子进程的数据与超时设置
*/
//主进程文件
$child_file = "echo.php";
$descriptorspec = array(
    0 => array("pipe", "r"),        // 标准输入,子进程从此管道中读取数据
    1 => array("pipe", "w"),        //STDOUT     标准输出,重定向子进程输入到主进程STDOUT
    2 => array("file", "error-output.txt", "a")         // 标准错误,写入到一个文件
);
//生成子进程。
$child_process = proc_open("php {$child_file}", $descriptorspec, $pipes);
/*
//write
while(1){
    $time = date("Y-m-d h:i:s");
    fwrite($pipes[0], "main say {$time}\n");
    sleep(1);
}
*/
//$cotent = stream_get_contents($pipes[1], 5);  //可用于阻塞读取
//var_dump($cotent);
stream_set_blocking($pipes[1], 0);   //非阻塞
$read = array($pipes[1]);
$write = null;
$except = null;
$timeleft = 0;
$stdout_str = '';
//$endtime = time() + $timeout;
do {
    //$timeleft = $endtime - time();
    //等待调度
    $ret = stream_select(
        $read,
        $write,
        $except,
        $timeleft
    );
    if ($ret === false) {
        $err = true;
        break;
    } else if ($ret === 0) {
        $timeleft = 0;
        break;
    } else {
        //把输出一次的数据一次读取完,按照fread读取的数量分次数。
        foreach ($read as $sock) {
            if ($sock === $pipes[1]) {
                //$stdout_str .= fread($sock, 4096);
                $stdout_str = fread($sock, 4096);
                var_dump($stdout_str);
            }
        }
    }
}while((feof($pipes[1]) === false));
//}while(feof($pipes[1]) === false  && $timeleft > 0);
proc_close($child_process);
echo.php
<?php
ob_implicit_flush(true);
$i = 0;
while(1){
    //while($stdin = fread(STDIN, 65535)){
        if ($i > 2) exit();
        echo str_repeat('*', 100)."\t$i\techo\n";
        sleep(1);
    //}
    $i++;
}
                    
                

                
            
        
浙公网安备 33010602011771号