<?php /** * Created by PhpStorm. * User: whitneywang * Date: 2018/6/4 * Time: 14:14 */
//第二个参数为true时,不输出TODO里的输出内容,显示会放到管道中 $process = new swoole_process(function (swoole_process $pro) { //todo //开启HTTPserver 类似在linux里运行一个PHP文件 //exec第二个参数要为数组 //Swoole\Process::exec() expects parameter 2 to be array $pro->exec('/home/work/bin/php',[ __DIR__.'/../server/http.php']); }, false); $pid = $process->start(); print_r($pid); //回收子进程 swoole_process::wait();
第二个参数为true只输出进程PID:
第二个参数为false
输出子进程
ps aux | grep process/process.php 可以看主进程 15594 就是上面15595的父进程
pstree -p 15594 通过子进程ID,可看到树结构
ps aft | grep http
场景:
curl
<?php class Curl { const URLS = [ 'http://baidu.com', 'http://qq.com', 'http://sina.com.cn' ]; function __construct() { echo 'process start time ' . time("Ymd H:i:s").PHP_EOL; } /** * 闭包里不好直接用变量,要用use * @return bool */ public function execute() { $workers = []; foreach (self::URLS as $key => $val) { $process = new swoole_process(function (swoole_process $pro) use ($key, $val) { //curl $content = $this-> curlData($val); echo $content . PHP_EOL; $pro->write($content. PHP_EOL); //$pro->write也可以直接输出管道里的内容 }, true); //true的情况下,输出信息会在管道里 $pid = $process->start(); $workers[$pid] = $process; } // 获取管道里的内容 foreach ($workers as $pros) { print_r($pros->read()); } echo 'process end time ' . time("Ymd H:i:s"); } /** * 模拟CURL请求 * @param $url * @return string */ function curlData($url) { //正常这里写CURL 或者file_get_content sleep sleep(1); return $url . ' succ'.PHP_EOL; } } $ws = new Curl(); $result = $ws->execute(1, 'test'); print_r($result . PHP_EOL); echo 'start:' . PHP_EOL;