1

我有一个依赖于 shell_exec() 的 PHP 脚本,并且(因此)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 读取。你可以看到我在这个线程中尝试过的内容:

只要创建了 png,就让 PHP proc_open() 读取 PhantomJS 流

我无法让它工作,似乎没有其他人可以为我提供解决方案。所以我现在要问的是如何让 proc_open 像 shell_exec 一样同步工作。我需要仅在 proc_open 命令结束后执行脚本中剩余的 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();
  }
}

这是 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();
});

如果不是“c:\phantomjs\phantomjs.exe /test.js”,而是使用 cmd.exe ping 表单示例,我会逐行打印 $return_message,所以我知道 proc_open 接收到一个流。我试图让幻影脚本也发生同样的事情。

4

0 回答 0