Home  >  Article  >  Backend Development  >  An in-depth analysis of the pcntl_fork() function in php

An in-depth analysis of the pcntl_fork() function in php

青灯夜游
青灯夜游forward
2021-02-25 17:58:103008browse

This article will introduce you to the pcntl_fork() function in PHP and understand its execution process. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

An in-depth analysis of the pcntl_fork() function in php

[Recommended learning: "PHP Video Tutorial"]

pcntl_fork() function is php- Functions in the pcntl module used to create processes. (Windows is not supported)

As for how to install and enable the php_pcntl extension, I will not introduce it here. I will only analyze the pcntl_fork() function itself.

$one = 123;
$one++;
$two = time();
$pid = [];
$pid = pcntl_fork();
$three = time();

When: pcntl_fork() function is executed, a child process will be created. The child process will copy everything about the current process, that is, the parent process: data, code, and state.

1. When pcntl_fork() successfully creates a child process, the child process number is returned in the parent process, 0 is returned in the child process, and -1 is returned if it fails

2 .The child process will copy the code and data of the parent process. Then it means: the code and data owned by the child and parent processes will be exactly the same.

3.Key points: The child process will copy the status of the parent process, then there is the above sample code: In the fifth line, pcntl_fork is executed, then The code of the created subprocess is also executed from the fifth line. The child process copied the data and code. Therefore, in the same way, there are variables such as $one, $two and so on in the sub-process

for ($i = 0; $i < 3; $i++) {
    $pid = pcntl_fork();
}
sleep(30);

So: How many sub-processes will actually be generated by the above for loop? The answer is 7. Under Linux, you can use the ps command to see 8 processes (1 parent process, 7 child processes)

Reason: The parent process creates a child process when i = 0 0, the child process at this time will continue to execute the loop. Create your own child process. In the same way: this will also happen when i=1...

For more programming-related knowledge, please visit: Introduction to Programming! !

The above is the detailed content of An in-depth analysis of the pcntl_fork() function in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete