swoole之创建子进程

一、代码

<?php

/**
 * 进程就是正在运行的程序的一个实例
 * 比如,在某个终端中执行一个PHP脚本,可以认为就是开启了一个进程,会有对应的进程id(pid)
 *
 * swoole进程与进程之间是通过管道通信
 */

 /**
  * 执行process.php 创建子进程$pid 子进程创建http_server
  *
  * php(11440,主进程)───php(11441,子进程)─┬─php(11442,manager进程)─┬─php(11444,worker进程)
  *                                      │                        ├─php(11445)
  *                                      │                        ├─php(11446)
  *                                      │                        └─php(11447)
  *                                      └─{php}(11443)
  */

$process = new swoole_process(function (swoole_process $worker) {
    // 执行 php http.php 开启http服务器
    $worker->exec("/usr/local/php71/bin/php", [__DIR__.'/../server/http.php']);
}, true);

$pid = $process->start();
echo $pid.PHP_EOL;

swoole_process::wait();

/**
 * 模拟爬取多个网站的数据场景
 */
$urls = [
    'http://www.helloweba.net/php/576.html',
    'http://www.helloweba.net/php/580.html',
    'http://www.helloweba.net/php/581.html'
];

$workers = [];

echo 'process start: '.date('Y-m-d H:i:s').PHP_EOL;

for ($i=0; $i<count($urls); $i++) {
    $url = $urls[$i];
    $process = new swoole_process(function (swoole_process $worker) use ($url) {
        $content = curlData($url);
        // echo $content.PHP_EOL;
        $worker->write($content);
    }, true);
    $pid = $process->start();
    $workers[$pid] = $process;
}

foreach ($workers as $process) {
    echo $process->read();
}

/**
 * 简化模拟请求
 * @param [type] $url
 * @return void
 */
function curlData($url)
{
    sleep(1);
    return "get {$url} content success".PHP_EOL;
}

echo 'process end: '.date('Y-m-d H:i:s').PHP_EOL;

/*
 输出数据,用时1秒(多进程执行)而不是3秒:
 process start: 2019-05-05 18:02:42
 get http://www.helloweba.net/php/576.html content success
 get http://www.helloweba.net/php/580.html content success
 get http://www.helloweba.net/php/581.html content success
 process end: 2019-05-05 18:02:43
 */

原文地址:https://www.cnblogs.com/cshaptx4869/p/10815350.html