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
1 CD php-version/ext/pcntl 2 phpize 3 ./configure && Make && make install 4 cp/usr/lib/php/modules/pcntl.so/usr/lib64/php/ Modules/pcntl. so 5 Echo "Extension=pcntl.so" >>/etc/php. INI 6 /ETC/INIT.D/HTTPD restart
It's very convenient.
Here is the sample code:
1<?PHP2 Header(' Content-type:text/html;charset=utf-8 ' ); 3 4 //extension must be loaded5 if(!function_exists("Pcntl_fork")) { 6 die("Pcntl extention is must!")); 7 } 8 //the number of total processes9 $totals= 3; Ten //number of scripts executed One $CMDARR=Array(); A //an array of the number of scripts executed - for($i= 0;$i<$totals;$i++) { - $CMDARR[] =Array("Path" = __dir__. "/run.php", ' pid ' =$i, ' total ' =$totals); the } - - /* - Expand: $cmdArr + Array - ( + [0] = = Array A ( at [path] =/var/www/html/company/pcntl/run.php - [PID] = 0 - [Total] = 3 - ) - - [1] = = Array in ( - [path] =/var/www/html/company/pcntl/run.php to [PID] = 1 + [Total] = 3 - ) the * [2] = = Array $ ( Panax Notoginseng [path] =/var/www/html/company/pcntl/run.php - [PID] = 2 the [Total] = 3 + ) A the ) + */ - $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 and child processes will execute the following code the if($pid= =-1) { - //error Handling: Returns 1 when creating a child process failure. Wuyi die(' could not fork '); the}Else if($pid) { - //The parent process gets the child process number, so this is the logic that the parent process executes Wu //If you do not need to block the process and want the exit status of the child process, you can comment 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. About}Else { $ //the child process gets a $pid of 0, so here is the logic that the child process executes. - $path=$cmd["Path"]; - $pid=$cmd[' PID '] ; - $total=$cmd[' Total '] ; A Echo exec("/usr/bin/php {$path} {$pid} {$total}")." \ n "; + Exit(0) ; the } - } $?>
PHP Multi-process implementation of pro-test