Basic use of Pcntl multiprocess extension in PHP

PHP provides a pcntl extension. Pcntl is based on Linux process. Windows system does not have this extension for the time being. It is used to realize basic multi process implementation. This can be used to process a very time-consuming task, such as sending and subscribing e-mail, SMS, in station information, etc.

Reference link:

http://php.net/manual/zh/ref....

http://php.net/manual/zh/ref....

http://blog.csdn.net/huyanpin...

http://rango.swoole.com/archi...

https://www.lvtao.net/dev/php...

Example code:

The code is based on the Laravel framework, which is recommended to allow this part of the code.

public function index(Request $request)

    {

        pcntl_signal(SIGCHLD, SIG_IGN); //If the parent process doesn't care when the child process ends, the kernel will recycle after the child process ends.  

        $max = 8000;

        $workers = 10;

        

        $pids = array();

        for($i = 0; $i < $workers; $i++){

            $pids[$i] = pcntl_fork();

            $pid = posix_getpid();

            switch ($pids[$i]) {

                case -1:

                    echo "fork error : {$i} \r\n";

                    exit;

                case 0:

                    $param = array(

                        'lastid' => $max / $workers * $i,

                        'maxid' => $max / $workers * ($i+1),

                    );

                    $this->doSomething($pid, $param);

                    exit;

                default:

                    break;

            }

        }

        

        foreach ($pids as $i => $pid) {

            if($pid) {

                //The parent process will get the child process number, so here is the logic of the parent process execution  

                //If you don't need to block a process and want to get the exit status of a child process, you can comment out the pcntl Ou wait ($status) statement, or write it as follows:  

                pcntl_wait($status,WNOHANG); //Wait for the subprocess to be interrupted to prevent the subprocess from becoming a zombie process.

                //pcntl_waitpid($pid, $status);

            }

        }

    }



// You can see what data that subprocess is processing

    public function doSomething($filename, $param)

    {

        for ($i = $param['lastid']; $i < $param['maxid']; $i++) {

            $path = "./test/";

            if (!is_dir($path)){

                mkdir($path, 0777, true);

            }

            $content = $i . '|';

            $file = $path . $filename . ".txt";

            file_put_contents($file, $content, FILE_APPEND);

        }

    }

It's more recommended to read documents, processes and threads, as well as many other contents, which need reading to learn

Tags: PHP Linux Windows Laravel

Posted on Sat, 30 Nov 2019 18:36:08 -0800 by saadlive