1. Overview of the pcntl_fork function in PHP
The pcntl_fork() function is a function in PHP that is used to create a child process and returns the pid of the created child process.
The specific fork process of this function creating a child process:
(1) Calling this function creates a child process. If the creation is successful, the parent process returns the pid of the child process, and the child process returns 0. ;
(2) Creating a child process is actually a copy of the parent process, sharing the code space and copying the data of the parent process. In other words, if the parent process changes the data of the parent process, the child process will change Subprocess
2. Sample code analysis
1. Code sample:
$curr_pid?=?posix_getpid( );//Get the current process id
//Write the current process id to the file
echo?'Current process:'.$curr_pid.PHP_EOL;
//Start creating a child process
$son_pid?=?pcntl_fork();//Return the id of the child process
//View the current process
< p>echo?'After creating the child process, the current process is:'.posix_getpid().PHP_EOL;//After creating the child process
if($son_pid?>? 0){
echo?'Son process id: '.$son_pid.PHP_EOL;
}
2. The result after the above code is executed is: p>
3. Sample code analysis:
(1) It is found that after creating a sub-process, the system will switch to the sub-process, and the code in the sub-process is from the line containing the pcntl_fork function Executed
(2) After creating a child process, the code segment of the child process is to copy the pcntl_fork function and the subsequent code segments. The previous code segment is not copied, but the specific data variables will still be copied by the child process.
(3) It can be seen that after fork, the program will fork for execution, that is, child process execution
3. Examples of business scenarios of pcntl_fork
1.php In the process, pcntl_fork is commonly used to achieve concurrency, and is mostly used for the implementation of some simple tools.
2. For example, if a monitoring tool wants to monitor several different indicators, you can use the main process to monitor the configuration changes of each indicator, and then fork a sub-process for each indicator to monitor its specific situation. , when the main process finds that the configuration of the indicator has changed, it will kill the previous sub-process and re-create the sub-process for monitoring.
3. The main process performs business distribution operations, and the sub-process performs specific business logic execution.
? (BY Sanxing MOOC)