1. 程式人生 > >php使用多進程(pcntl)

php使用多進程(pcntl)

php使用多進程(pcntl)

<?php /** * this is a demo for php fork and pipe usage. fork use * to create child process and pipe is used to sychoroize * the child process and its main process. * @author bourneli * @date: 2012-7-6 */ define("PC", 10); // 進程個數 define("TO", 4); // 超時 if (!function_exists(‘pcntl_fork‘)) { die("pcntl_fork not existing"); } // 創建管道 $sPipePath = "my_pipe.".posix_getpid(); if (!posix_mkfifo($sPipePath, 0666)) { die("create pipe {$sPipePath} error"); } // 模擬任務並發 for ($i = 0; $i < PC; ++$i ) { $nPID = pcntl_fork(); // 創建子進程 if ($nPID == 0) { // 子進程過程 for($j=0;$j<99999;$j++){ touch("test/{$i}{$j}.txt"); } $oW = fopen($sPipePath, ‘w‘); fwrite($oW, $i."\n"); // 當前任務處理完比,在管道中寫入數據 fclose($oW); exit(0); // 執行完後退出 } } // 父進程 $oR = fopen($sPipePath, ‘r‘); stream_set_blocking($oR, FALSE); // 將管道設置為非堵塞,用於適應超時機制 $sData = ‘‘; // 存放管道中的數據 $nLine = 0; $nStart = time(); while ($nLine < PC && (time() - $nStart) < TO) { $sLine = fread($oR, 1024); if (empty($sLine)) { continue; } echo "current line: {$sLine}\n"; // 用於分析多少任務處理完畢,通過‘\n’標識 foreach(str_split($sLine) as $c) { if ("\n" == $c) { ++$nLine; } } $sData .= $sLine; } echo "Final line count:$nLine\n"; fclose($oR); unlink($sPipePath); // 刪除管道,已經沒有作用了 // 等待子進程執行完畢,避免僵屍進程 $n = 0; while ($n < PC) { $nStatus = -1; $nPID = pcntl_wait($nStatus, WNOHANG); if ($nPID > 0) { echo "{$nPID} exit\n"; ++$n; } } // 驗證結果,主要查看結果中是否每個任務都完成了 $arr2 = array(); foreach(explode("\n", $sData) as $i) {// trim all if (is_numeric(trim($i))) { array_push($arr2, $i); } } $arr2 = array_unique($arr2); if ( count($arr2) == PC) { echo ‘ok‘; } else { echo "error count " . count($arr2) . "\n"; var_dump($arr2); }

php使用多進程(pcntl)