This article mainly introduces the PHP Pcntl Process Control of the multi-process consumption model, has a certain reference value, and now share to everyone, the need for friends can refer to
Multi-process consumption model
the parent process waits and controls the exit of the child process
Idea Finishing
after the parent process is turned on, get the PID of the child process directly, and then save the child, the sub-process fork out directly open the business consumption code, and then exit (0) quit, and then the parent process pcntl_wait wait for the child process exit, all exit stepfather process end
Code
Const NEWLINE = "\ n"; if (Strtolower (Php_sapi_name ()) = ' cli ') {die ("Please run in CLI mode");} $bizPath = "./childbiz/", if (!is_dir ($bizPath)) {@mkdir ($bizPath, 0755, true);} $child = []; $index = 0; $loop = 10; Number of child processes//If it is a variable of resource type, the parent-child process will share//$f = fopen ("./pcntl_fork_2.php", "R"), while ($index < $loop) {echo "Current process:". Getmypid () . NEWLINE; $pid = Pcntl_fork (); Fork out child process//fork stepfather process will go their own logic, the child process from the beginning of their own logic, the stack information will be completely copied to the child process memory space, the parent-child process is independent of each other if ($pid = =-1) {//Create error, Return-1 die (' Process F Ork failed '); } else if ($pid) {//$pid > 0, if Fork succeeds, returns the child process ID//Gets the child process created $child [$pid] = $pid; echo "{$pid} child create!". Microtime (True). NEWLINE; } else {//$pid = 0//child process Logic $sleepTime = rand (5, 18); Sleep ($sleepTime); $time = Microtime (true); File_put_contents ($bizPath. Getmypid (). ". Log ", $time. ":" . $index. Php_eol, File_append); Exit (0); } $index + +;} while (count ($child)) {//block wait $pid = pcntl_wait ($status); $time = Microtime (True); File_put_contents ("./father.log", $time. ":" . $pid. ":" . $status. Php_eol, File_append); if ($pid > 0) {unset ($child [$pid]); } if ($pid = =-1) {unset ($child); }//foreach ($child as $k + $pid) {////non-blocking loop determination Wnohang indicates that if no child process exits immediately return//$res = Pcntl_waitpid ($pid, $ status, Wnohang);//$time = Microtime (TRUE);//File_put_contents ("./father.log", $time. ":" . $pid. ":" . $res. ":" . $status. Php_eol, file_append);//if ( -1 = = $res | | $res > 0) {//unset ($child [$k]);//}//}}//fclos E ($f);//The main process exits exit (0);
The above is the whole content of this article, I hope that everyone's learning has helped, more relevant content please pay attention to topic.alibabacloud.com!