它更多是C
或glibc
问题。你将不得不使用fflush(stdout)
。
为什么?在终端中运行a.out
并从PHP中调用它有什么区别?
答案:如果你在终端运行a.out
(是stdin a tty),那么glibc将使用线路缓冲的IO。但是如果你从另一个程序(在这种情况下是PHP)运行它,并且它的标准输入是一个管道(或者其他什么,但不是一个tty)比glibc将使用内部IO缓冲。这就是为什么第一个fgets()
块如果未注释。欲了解更多信息,请点击这里article。
好消息:您可以使用stdbuf
命令控制此缓冲。更改$run_string
到:
$run_string = "cd ".$addr_base.";stdbuf -o0 ./a.out 2>&1";
这里来工作的例子。工作,即使它是使用stdbuf
命令C代码不关心fflush()
:
启动子
$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);
}
}
是您的“用户”,从网站互动?因为通过这种方式,用户似乎不能直接访问服务器的'STDIN'。 – Passerby 2013-05-03 04:13:19
@Passerby用户按下按钮进行编译,并输入_x_并将其发送到服务器。但是在输入_x_之前,服务器必须首先从'STDIN'获取流并将其发送到网站,以便用户知道他应该输入_x_。问题是服务器无法在那一刻得到流.. – dahui 2013-05-03 04:39:52