1

我有一个 PHP 脚本,它依赖shell_exec()并且(因此)99% 的时间都在工作。该脚本执行了一个生成图像文件的 PhantomJS 脚本。然后使用更多的 PHP 以某种方式处理该图像文件。问题是有时shell_exec()会挂起并导致可用性问题。阅读此 https://github.com/ariya/phantomjs/issues/11463 我了解到这shell_exec()是问题所在,切换到proc_open将解决挂起问题。

问题是shell_exec()等待执行的命令完成时proc_open不会,因此跟随它并在生成的图像上工作的 PHP 命令会失败,因为图像仍在生成中。我在 Windows 上工作,所以pcntl_waitpid不是一个选择。

我正在尝试做的是不断地让 PhantomJS 输出一些东西(任何东西),以便proc_open通过它的标准输入管道读取,这样我就可以在目标图像文件准备好后立即开始工作的图像处理 PHP 函数。

这是我的 phantomJS 脚本:

interval = setInterval(function() {
  console.log("x");
}, 250);
var page = require('webpage').create();
var args = require('system').args;
page.open('http://www.cnn.com', function () {
  page.render('test.png');
  phantom.exit();
});

还有我的 PHP 代码:

ob_implicit_flush(true);
$descriptorspec = array(
    0 => array("pipe", "r"),  // stdin
    1 => array("pipe", "w"),  // stdout
    2 => array("pipe", "w")   // stderr 
);

$process = proc_open ("c:\phantomjs\phantomjs.exe /test.js", $descriptorspec, $pipes);
if (is_resource($process))
{
while( ! feof($pipes[1]))
  {
     $return_message = fgets($pipes[1], 1024);
     if (strlen($return_message) == 0) break;
     echo $return_message.'<br />';
     ob_flush();
     flush();
  }
}

生成了 test.png,但我没有得到一个$return_message. 我究竟做错了什么?

4

1 回答 1

1

正如Bill Shander在您链接的 github 问题中建议的那样,您可以使用:

Proc_Close(Proc_Open("phantomjs test.js &", Array (), $foo));

运行您的 phantomjs 脚本(基于此答案)。似乎您只需要图像,因此在这种情况下不需要管道。

供参考的完整脚本在这里,可以在 Windows 上按原样工作。

于 2014-08-01T16:08:49.683 回答