Home  >  Article  >  Backend Development  >  Do you know pcntl_fork in php?

Do you know pcntl_fork in php?

慕斯
慕斯forward
2021-05-24 15:29:412806browse

#About the pcntl_fork() function is php- Functions in the pcntl module used to create processes. This article will lead you into the mysteries of PHP, let’s go together! ! !

Do you know pcntl_fork in php?

The pcntl_fork() function is the function used to create a process in the php-pcntl module. (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, the same exists in the child process: $one, $two and other variables

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

那么:上面的for循环,实际会产生多少个子进程?答案是7个,在linux下,用ps命令将可以看到8个进程(1个父进程,7个子进程)
Reason: The parent process is at ​ ​ ​​ ​​ i ​​ ​​ = ​​ ​​ 0 ​​ ​​ hour ​​ ​​ , ​​ ​​ Create ​​ ​​ establish ​​ ​​ out ​​ ​​ one ​​ ​​ indivual ​​ ​​ son ​​ ​​ Enter ​​ ​​ Procedure ​​ ​​ 0 ​​ ​​ , ​​ ​​ this ​​ ​​ hour ​​ ​​ of ​​ ​​ son ​​ ​​ Enter ​​ ​​ Procedure ​​ ​​ , ​​ ​​ return ​​ ​​ meeting ​​ ​​ Continuation ​​ ​​ Continued ​​ ​​                     ​​ ​​ OK ​​ ​​ Circulation ​​ ​​ ring ​​ ​​ . ​​ ​​ Create ​​ ​​ establish ​​ ​​ out ​​ ​​ Genus ​​ ​​ At ​​ ​​ since ​​ ​​ Has ​​ ​​ of ​​ ​​ son ​​ ​​ Enter ​​ ​​ Procedure ​​ ​​ . ​​ ​​ same ​​ ​​ reason ​​ ​​ : ​​ ​​ ​​ When i=0, a child process 0 is created. At this time, the child process will continue to execute the loop. Create your own child process.Same reason: ​ i##= 0 When,Createbuild0this When ’s son enters Cheng, returns to ContinueContinueexecutelooploop. Createbuildoutbelong to #子. Same as : This will also happen when i=1...

Recommended learning: "

PHP video tutorial"

The above is the detailed content of Do you know pcntl_fork 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