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
[Plain]View Plaincopy print?
- 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]View Plaincopy print?
- <?php
- Header (' Content-type:text/html;charset=utf-8 ');
- Extension must be loaded
- if (!function_exists ("Pcntl_fork")) {
- Die ("Pcntl extention is must!");
- }
- The number of total processes
- $totals = 3;
- 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
- [Total] = 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 and child processes will execute the following code
- if ($pid = =-1) {
- //Error handling: Returns 1 when creating a child process failure.
- Die (' could not fork ');
- } Else if ($pid) {
- //Parent process will get the child process number, so here is the logic that the parent process executes
- //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.
- } Else {
- //Sub-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 '];
- echo exec ("/usr/bin/php {$path} {$pid} {$total}")." \ n ";
- exit (0);
- }
- }
- ?>
PHP Multi-process implementation