Home  >  Article  >  Backend Development  >  How to implement multi-process in php

How to implement multi-process in php

王林
王林Original
2020-08-26 13:31:333319browse

How to implement multi-process in php: through pcntl and posix extensions. Depending on the needs, we can use the pcntl_fork() function to create a child process and the pcntl_wait() function to block the current process.

How to implement multi-process in php

#php multi-process requires pcntl, posix extension support.

Multi-process implementation can only be done in cli mode. In a web server environment, unexpected results may occur.

(Recommended video tutorial: php video tutorial)

Multi-process core function:

pcntl_fork (create child process), pcntl_wait( Block the current process)

Detailed introduction:

pcntl_fork:

A call returns twice, the child process pid is returned in the parent process, 0 is returned in the child process, and -1 is returned on error.

pcntl_wait ( int &$status [, int $options ] ):

Block the current process until any child process exits or receives a signal to end the current process. Note that it is a signal to end the current process, and the SIGCHLD sent by the child process to end is not counted. Use $status to return the status code of the child process, and you can specify the second parameter to indicate whether it is called in a blocking state.

The function return value is the pid of the child process. If there is no child process, the return value is Is -1;

Called in non-blocking mode, the function can also return 0 when a child process is running but has not ended.

pcntl_waitpid ( int $pid , int &$status [, int $options ] )

The function is the same as pcntl_wait, the difference is that waitpid is the child process waiting for the specified pid. When pid is -1, pcntl_waitpid is the same as pcntl_wait. The status information of the child process is stored in $status in the pcntl_wait and pcntl_waitpid functions.

(Recommended related tutorials: php graphic tutorial)

Example:

A fixed number of child processes are always running in

php.

Use core functions such as pcntl_fork (create child process), pcntl_wait (block the current process) as needed

###Code implementation: ###
= $maxChildPro) {
            pcntl_wait($status);
        }
    } else {
//子进程运行代码
        $s = rand(2, 6);
        sleep($s);
        echo "child sleep $s second quit", PHP_EOL;
        exit;
    }
}

The above is the detailed content of How to implement multi-process in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn