它更多的是一个C
or a glibc
问题。你必须使用fflush(stdout)
.
为什么?和跑步有什么区别a.out
在终端中并从 PHP 调用它?
答:如果你跑步a.out
在终端(作为 stdin 和 tty)中,glibc 将使用行缓冲 IO。但是,如果您从另一个程序(在本例中为 PHP)运行它,并且它的 stdin 是一个管道(或其他但不是 tty),那么 glibc 将使用内部 IO 缓冲。这就是为什么第一个fgets()
如果未注释则阻塞。欲了解更多信息,请检查此article.
好消息:您可以使用以下命令控制此缓冲stdbuf命令。改变$run_string
to:
$run_string = "cd ".$addr_base.";stdbuf -o0 ./a.out 2>&1";
这是一个工作示例。即使 C 代码不关心也能工作fflush()
因为它正在使用stdbuf
命令:
启动子进程
$cmd = 'stdbuf -o0 ./a.out 2>&1';
// what pipes should be used for STDIN, STDOUT and STDERR of the child
$descriptorspec = array (
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("pipe", "w")
);
// open the child
$proc = proc_open (
$cmd, $descriptorspec, $pipes, getcwd()
);
将所有流设置为非阻塞模式
// set all streams to non blockin mode
stream_set_blocking($pipes[1], 0);
stream_set_blocking($pipes[2], 0);
stream_set_blocking(STDIN, 0);
// check if opening has succeed
if($proc === FALSE){
throw new Exception('Cannot execute child process');
}
获取子进程 pid。我们稍后需要它
// get PID via get_status call
$status = proc_get_status($proc);
if($status === FALSE) {
throw new Exception (sprintf(
'Failed to obtain status information '
));
}
$pid = $status['pid'];
轮询直到子进程终止
// now, poll for childs termination
while(true) {
// detect if the child has terminated - the php way
$status = proc_get_status($proc);
// check retval
if($status === FALSE) {
throw new Exception ("Failed to obtain status information for $pid");
}
if($status['running'] === FALSE) {
$exitcode = $status['exitcode'];
$pid = -1;
echo "child exited with code: $exitcode\n";
exit($exitcode);
}
// read from childs stdout and stderr
// avoid *forever* blocking through using a time out (50000usec)
foreach(array(1, 2) as $desc) {
// check stdout for data
$read = array($pipes[$desc]);
$write = NULL;
$except = NULL;
$tv = 0;
$utv = 50000;
$n = stream_select($read, $write, $except, $tv, $utv);
if($n > 0) {
do {
$data = fread($pipes[$desc], 8092);
fwrite(STDOUT, $data);
} while (strlen($data) > 0);
}
}
$read = array(STDIN);
$n = stream_select($read, $write, $except, $tv, $utv);
if($n > 0) {
$input = fread(STDIN, 8092);
// inpput to program
fwrite($pipes[0], $input);
}
}