并行运行多个 PHP 进程 [英] Running several PHP processes in parallel

查看:74
本文介绍了并行运行多个 PHP 进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在用 PHP 编写一个与 SEO 相关的脚本,一旦我们完成了抓取过程,我们需要同时运行不同的模块(每个模块都是一个 .php 文件).换句话说,我们需要并行执行 10 个以上的 .php 文件.

We're working on a SEO related script in PHP, and we need to run different modules (each one of them are a file .php) at the same time once we finish with the crawling process. In other words, we need to execute more than 10 .php files, in parallel.

该应用程序过去使用一个序列,因此当一个脚本结束时,用户的浏览器会被转发到下一个.每个脚本都在建立与数据库的连接,并向被爬取的 Web 应用程序发送不同的 HTTP 数据包.

The application used to work with a sequence, so once when one script was ending, the user's browser was forwarded into the next one. Each one of the scripts is establishing a connection to the database, and sending different HTTP packets to the crawled web application.

我知道可以使用 popen 来解决这个问题?有什么方法可以将每个模块的信息接收到触发它们的主脚本中?谁能提供一个非常简短的片段来看看这将如何工作?

I understand that this could be approached using popen? Is there any way to receive information from each one of this modules into the main script that triggers them? Could anyone provide a very short snippet to see how this would work?

推荐答案

如果 PHP 中的各个文件都没有依赖,我想你可以使用 multi-curl 的方法,可以实现如图 :-

If the various files in PHP have no dependency, I think you can use a multi-curl approach which can be implemented as shown :-

    $linkArray = array('file1.php', 'file2.php','file3.php','file4.php','file5.php');
    $nodes = ($linkArray);
    $node_count = count($nodes);

    $curl_arr = array();
    $master = curl_multi_init();
    $counter = 0;
    for($i = 0; $i < $node_count; $i++)
    {
      $url =$nodes[$i];
      $curl_arr[$i] = curl_init($url);
      curl_setopt($curl_arr[$i], CURLOPT_RETURNTRANSFER, true);
      curl_multi_add_handle($master, $curl_arr[$i]);
    }

do {
    curl_multi_exec($master,$running);
} while($running > 0);

for($k=0;$k<$node_count;$k++){

  $result = curl_multi_getcontent  ($curl_arr[$k]); // contains the output of individual files

}

这篇关于并行运行多个 PHP 进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆