We used fsockopen to simulate multi-process concurrency. However, in the process of use, you may also find that it has a fatal defect, and this defect cannot be solved. That is, the services sent and released are uncontrollable and cannot be queried or killed.
In PHP's simple method for simulating multithreading, we have handed in the use of fsockopen to simulate multi-process concurrency. However, in the process of use, you may also find that it has a fatal defect, and this defect cannot be solved. That is, the services sent and released are uncontrollable and cannot be queried or killed. The reason for this defect is that fsockopen is used to simulate multi-process concurrency. Send only services, regardless of the results.
Recently, I checked some information about the implementation of multi-process php on the internet and found that php has already provided us with an extension called pcntl and implemented this operation.
Note that this extension can only run in linux, but not in windows. For more information about how to add pcntl extensions, see how to add php extensions in linux (taking pcntl as an example.
Today, I will show you an example of using phppcntl extension to implement multiple processes. the code is as follows:
// Both the parent and child processes execute the following code:
$ Pid = pcntl_fork ();
// Error handling:-1 is returned when the sub-process fails to be created.
If ($ pid =-1)
{
Die ('could not fork ');
}
// The parent process will get the sub-process number, so here is the logic of the parent process execution
Elseif ($ pid)
{
}
// The $ pid obtained by the sub-process is 0, so here is the logic of the sub-process execution.
Else
{
Sleep (3 );
Echo 'C'. time (). "\ r \ n ";
}
?>
Let's explain:
Pcntl_fork (): generate a branch (sub-process) at the current position of the current process ). Note: fork creates a sub-process. both the parent process and the sub-process continue to execute from the fork position. The difference is that during the execution of the parent process, the fork returned value is the sub-process number, and the sub-process gets 0. [This is the explanation of pcntl_fork () function in the php Manual]
We should be able to understand it with the comments of the program. The current process number returned by the main process. Therefore, after elseif ($ pid) is the code block of the main process; when the sub-process returns 0, the code block of the sub-process executed after else is used.
Note the following:
The above program can only be executed directly through php, but not through apache.