ps -ef | grepperhaps
pstree -apn | grepIt must have been used in general, and the printed one is like this:
One in the picture above
masterThe following two branches are the child process.
Those who have used workman are also familiar with the above structure. The bottom layer of workman is written in PHP, which depends on PHP extension
pcntlIt is one of the most important dependency extensions
workerThe structure is implemented by this extension.
Back to the point, use
pcntl_fork()Make it happen,
forkFork a subprocess, that is, to create a subprocess.
The above code is the official sample code, and the specific process is to execute to
pcntl_fork()Copy as like as two peas.
in other words
pcntl_fork();At the same time, the following code is executed in both processes (including
$pidThe assignments in the two processes are different, and they are returned in the parent process
$pidGreater than 0, equal to the process of the child process
idIt’s usually called
pid（process id）。 And the
ifThe logic of which role should be executed in which code block is distinguished by judgment.
masterIt is responsible for managing the number of subprocesses, processing signals and so on. It doesn’t process business logic, but
workerProcess, as the name suggests, work process.
A process structure similar to nginx has emerged
pcntl_wait($status);It is a function to prevent a child process from becoming a zombie process. It is blocked, similar to listening. That is, when the subprocess exits after execution, or actively
exit()The parent process assigns the capture status code to the
$statusAnd clean up the child processes.
The last point, mentioned earlier: execution to
pcntl_fork()A copy of the original document is “copied” at the same time. Note that the child process inherits the variables and methods of the parent process, but because it is two processes (two scripts), the reassignment of variables in the child process will not affect the value of variables in the parent process, and the processes are isolated.
You can see it printed first
1Is the output of the parent process, followed by
2Is the output of the child process.
This work adoptsCC agreementReprint must indicate the author and the link of this article