【发布时间】:2019-03-08 23:52:05
【问题描述】:
我正在尝试将节点进程中的内容通过管道传输到 PHP 脚本中,但由于某种原因它挂在 PHP 中并且似乎永远不会退出 test-stdin.php 中的 while 循环因此最终的 echo 语句 echo('Total input from stdin: ' . $text) 永远不会运行。
run.js
const { spawn } = require('child_process');
const php = spawn('php', ['test-stdin.php'], {});
php.stdin.write('some input');
php.stdin.write("\n"); // As I understand, EOL is needed to stop processing
// Also tried the below, didn't work.
// ls.stdin.write(require('os').EOL);
php.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
php.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
test-stdin.php
$input_stream = fopen("php://stdin","r");
stream_set_blocking($input_stream, 0); // Also tried: stream_set_blocking(STDIN, 0);
$text="";
// It never exits this loop, for some reason?
while(($line = fgets($input_stream,4096)) !== false) {
var_dump('Read from fgets: ', $line); // This dumps successfully "some input"
$text .= $line;
}
// The below code is never reached, as it seems it's hanging in the loop above.
fclose($input_stream);
echo('Total input from stdin: ' . $text);
任何想法为什么它挂在那个循环中并且没有达到最终的回声?我尝试将流设置为“非阻塞”模式,但似乎没有任何效果。
【问题讨论】: