This article mainly introduces the PHP multi-process implementation of programming examples, has a certain reference value, now share to everyone, the need for friends can refer to
PHP Multi-process implementation
PHP has a set of process control functions (–ENABLE-PCNTL and POSIX extensions are required at compile time), which enables PHP to create sub-processes like C in the Nginx system, execute programs using the EXEC function, and process signals.
CentOS 6 under the Yum install PHP, the default is not to install PCNTL, so you need to compile the installation separately, first download the corresponding version of PHP, after decompression
CD php-version/ext/pcntl phpize./configure && make && make install CP/USR/LIB/PHP/MODULES/PCNTL.SO/USR /lib64/php/modules/pcntl.so echo "extension=pcntl.so" >>/etc/php.ini/etc/init.d/httpd restart
It's very convenient.
Here is the sample code:
<?php header (' Content-type:text/html;charset=utf-8 '); You must load the extended if (!function_exists ("Pcntl_fork")) {die ("Pcntl extention is must!");//The number of total processes $totals = 3; The number of scripts executed $CMDARR = array (); An array of the number of scripts executed for ($i = 0; $i < $totals; $i + +) {$CMDARR [] = Array ("path" = __dir__. "/run.php", ' pid ' = $i, ' total ' = $totals); }/* Expand: $CMDARR Array ([0] = = Array ([path] =/var/www/html/company/pcntl/run.php [PID] + 0 [tot AL] + 3) [1] = = Array ([path] = =/var/www/html/company/pcntl/run.php [PID] = 1 [Total] = 3) [2] = = Array ([path] =/var/www/html/company/pcntl/run.php [PID] = 2 [total] + 3)) */Pcntl_signal (SIGCHLD, sig_ign); If the parent process does not care what time the child process ends, the kernel is reclaimed after the child process is finished. foreach ($cmdArr as $cmd) {$pid = Pcntl_fork ();///create child process//parent process and child process will execute the following code if ($pid = =-1) {//Error handling: Return-1 when creating a child process fails. Die (' could not fork '); The else if ($pid) {//parent process will get the child process number, so here is the logic for the parent process to execute///If you do not need to block the process and want the child process exit state, you canComment out the pcntl_wait ($status) statement, or write: Pcntl_wait ($status, Wnohang); Wait for the child process to break to prevent the child process from becoming a zombie process. The else {//Sub-process gets a $pid of 0, so this is the logic that the child process executes. $path = $cmd ["Path"]; $pid = $cmd [' pid ']; $total = $cmd [' Total ']; echo exec ("/usr/bin/php {$path} {$pid} {$total}"). " \ n "; Exit (0); }}?>