1

I start some pcntl process to calculate some data, and I want to wait all child process end ,and send all return data to master process.

How Can I do that?

my pnctl trait like that:

<?php namespace App\Console\Commands;

trait PcntlTrait
{
    private $workers = 1;

    public function worker($count)
    {
        $this->worker = $count;
    }

    public function pcntl_call($all, \Closure $callback)
    {
        $count = count($all);
        $perNum = ceil($count / $this->workers);

        for($i = 0; $i < $this->workers; $i++){
            $pids[$i] = pcntl_fork();
            switch ($pids[$i]) {
                case -1:
                    echo "fork error : {$i} \r\n";
                    exit;
                case 0:
                    $start = $i * $perNum;
                    return $callback(array_slice($all, $start, $perNum));
                    exit;
                default:
                    break;
            }
        }

        $ret = [];
        foreach ($pids as $i => $pid) {
            if($pid) {
                pcntl_waitpid($pid, $info);
                $ret = array_merge($ret, $info);
            }
        }

        return $ret;
    }
}

and my TestCase Like that:

<?php

use App\Console\Commands\PcntlTrait;

class PcntlImp
{
        use PcntlTrait;
}

class TestPcntlTrait extends \TestCase
{
    public function setup()
    {
        $this->createApplication();
    }

    public function testPcntlCall()
    {
        $arr = [1,2,3,4,5,6,7,8,9,10];

        $imp = new \PcntlImp();
        $imp->worker(1);

        $data = $imp->pcntl_call($arr, function($info){
            if (empty($info)){
                return [];
            }

            $ret = [];
            foreach ($info as $item) {
                $ret[] = $item * $item;
            }
            return $ret;
        });

        $this->assertCount(10, $data);
    }
}

But I can got the error:

array_merge(): Argument #2 is not an array

and I know the second arg of pcntl_wait function is status not return data. But I do not know how to do?

jianfeng
  • 2,440
  • 4
  • 21
  • 28

0 Answers0