CLI命令响应长字符串(18Kb),导致exec()返回空字符串


Long string (18Kb) response from CLI command - causes exec() to return empty string

这个问题让我非常头疼。看似简单的事情-但我不明白为什么它不起作用。我有一个小的c++守护进程监听127.0.0.1:3454请求并返回以分号分隔的单词列表。

我试图从PHP提供守护进程请求-但我遇到的是-如果守护进程返回大字符串- PHP得到的0长度字符串代替....我不明白....

// Doesn't work - empty string is returned...
$cmd = 'printf "ends a" | nc 127.0.0.1 3454';
exec($cmd, $out);
echo 'result is: ' . (empty($out) ? '' : $out[0]);
// Works - but why the should I use a file as an intermediary..?
$cmd = 'printf "ends a" | nc 127.0.0.1 3454 > /tmp/test.txt';
exec($cmd);
$res = file_get_contents('/tmp/test.txt');
echo 'result is: ' . $res;

此外-同样的命令:printf "ends a" | nc 127.0.0.1 3454 -在CLI中工作得很好…

注:因此,在上面的示例中,守护进程返回18645个字符-> PHP get的空字符串。但是当它返回较短的响应- PHP得到它们就可以了....?为什么?18645个字符并不多…

您可以尝试一个更面向I/O的函数,如popen

$read="";
$handle = popen('printf "ends a" | nc 127.0.0.1 3454');
while (!feof($handle)) {
    $read .= fread($handle, 1024);
}
echo $read;
pclose($handle);
编辑:

在read

上添加一个循环

尝试使用类似于exec (system、passthru、shell_exec)的函数之一,或者在将数据返回给exec之前压缩数据。

相关文章: