First, preface
We all know that PHP is a single-threaded execution, processing multiple concurrency is mainly dependent on the server or PHP-FPM multi-process and their process reuse, but PHP implementation of a multi-process is also significant, especially in the background CLI mode when processing large amounts of data or running the background Demon Daemon. cannot be applied in a Web server environment.
/**/if (substr(php_sapi_name(), 0, 3)!== ' CLI ') { die ("CLI mode only");}
In daily tasks, it is sometimes necessary to perform some log analysis, queue processing and other tasks through PHP scripts, which can be processed using multiple processes when the volume of data is large.
PHP multithreading has been mentioned, but in-process multi-threaded resource sharing and distribution problems difficult to solve. PHP also has multi-threaded extension pthreads, but it is said to be less stable and requires a thread-safe environment.
To implement multiple processes in PHP, you need to install PCNTL and POSIX extensions.
Second, create a child process
Use the Pcntl_fork () function to create a branch at the current location. Fork is the creation of a child process, the parent process and the child process start from the position of the fork to continue execution, different from the parent process, the resulting fork return value is the child process number, and the child process gets 0, execution failure is returned-1.
Because the system initial init process PID is 1, then all the process PID will be greater than the process, so you can pass the return value of pcntl_fork () greater than one to determine that the current process is the parent process, the return value equals zero is the child process.
$ppid= Posix_getpid ();//gets the ID of the current process$pid= Pcntl_fork ();//Create Child processif($pid= =-1) { Throw New Exception(' Fork sub-process failed! '));} ElseIf($pid> 0) { //Parent Process Execution LogicCli_set_process_title ("I am the parent process, my process ID is {$ppid}."); Sleep(30); Pcntl_wait ($status);//wait for the child process to break to prevent the child process from becoming a zombie process. }Else { //child Process Execution Logic $cpid=Posix_getpid (); Cli_set_process_title ("I am {$ppid}, my process ID is {$cpid}."); Sleep(30);}
Execution Result:
Note: If you create a child process in a loop, the child process ends up with exit to prevent the child process from entering the loop.
Iii. management of sub-processes
Manage child processes, using signals. In simple terms, the parent process uses two functions pcntl_signal () and Pcntl_signal_dispatch (), which is responsible for installing the signal processor and distribution work to the child process.
in computer science, signaling is a restrictive way of interprocess communication in Unix, Unix-like, and other POSIX-compliant operating systems. It is an asynchronous notification mechanism used to alert a process that an event has occurred.
We manage the child process by receiving a signal from the child process in the parent process and judging the state of the subprocess. We need to use the pcntl_signal () function and the Pcntl_signal_dispatch () function in the parent process to install the signal handlers for each sub-process:
// Install a signal processor, $signo is the signal constant to be processed, callback is its processing function $signo Callback $handler
// call each waiting signal to install the processor via pcntl_signal ()
Common signal Constants in PHP are:
- SIGCHLD: The child process exits as a zombie process sends this signal to the parent process
- SIGHUP: Process hangs
- Sigtem: Process Termination
Iv. processing of sub-processes
Two functions are required to process a subprocess:
// send $sig signal to process ID $pid process $pid $sig )
// suspends execution of the current process until a process with a process number of $pid exits (if $pid is-1, it waits for any child process) $pid, int &$status$options = 0])
The Posix_kill () function terminates a child process by sending a signal to the child process to manipulate the subprocess, optionally sending the process termination signal to the child process if necessary;
The Pcntl_waitpid () function waits or returns the sub-process state of the fork, if the specified child process has exited at this function call (commonly known as a zombie process), this function returns immediately and frees all system resources of the child process, which prevents the child process from turning into a zombie process, resulting in wasted system resources. This allows you to accomplish the task of working with the child process.
V. Examples
If a task is broken down into multiple process executions, it will reduce overall time-consuming. For example, there is a larger data file to be processed, this file consists of a number of lines. If a single process executes a task that is to be processed, it takes a long time to take a large amount. You can consider multiple processes at this point. Multi-process processing decomposition tasks, each process processing a portion of the file, so that the need to split the large file into multiple small files (the number of processes and small files equivalent).
For example, the file File.log has 100,000 rows of data and now wants to be processed in 4 processes. You need to split 25,000 lines of one file. Command split can do this:
<?PHPshell_exec(' Split-l 25000-d file.log prefix_name ');//3 Child process processing tasks for($i= 0;$i< 3;$i++){ $pid=pcntl_fork (); if($pid= =-1) { die("Could not fork"); } ElseIf($pid) { Echo"I ' m The Parent$i\ n "; } Else{//Child Process Processing $content=file_get_contents("PREFIX_NAME0".$i); //business Process begin//Business process End Exit;//Be sure to pay attention to the exit subprocess, otherwise pcntl_fork () will quilt the process again fork, bring the impact of processing. }}//wait for the child process to finish executing while(Pcntl_waitpid (0,$status)! =-1) { $status= Pcntl_wexitstatus ($status); EchoThe child$statusCompleted\n ";}
Reference:
"PHP Multi-process Summary": https://www.cnblogs.com/leezhxing/p/5223289.html
"A probe into PHP multi-process": https://www.cnblogs.com/zhenbianshu/p/5676822.html
PHP using multi-process processing tasks: https://www.cnblogs.com/firstForEver/p/7301630.html
PHP Multi-Process Preliminary