標籤:company fork exe data 執行 highlight 系統 數組 enable
PHP多進程實現
php有一組進程式控制制函數(編譯時間需要–enable-pcntl與posix擴充),使得php能在nginx系統中實現跟c一樣的建立子進程、使用exec函數執行程式、處理訊號等功能。
CentOS 6 下yum安裝php的,預設是不安裝pcntl的,因此需要單獨編譯安裝,首先下載對應版本的php,解壓後
[plain] view plain copy 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
方便極了。
下面是範例程式碼:
[php] view plain copy print?
- <?php
- header(‘content-type:text/html;charset=utf-8‘ );
-
- // 必須載入擴充
- if (!function_exists("pcntl_fork")) {
- die("pcntl extention is must !");
- }
- //總進程的數量
- $totals = 3;
- // 執行的指令碼數量
- $cmdArr = array();
- // 執行的指令碼數量的數組
- for ($i = 0; $i < $totals; $i++) {
- $cmdArr[] = array("path" => __DIR__ . "/run.php", ‘pid‘ =>$i ,‘total‘ =>$totals);
- }
-
- /*
- 展開:$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); //如果父進程不關心子進程什麼時候結束,子進程結束後,核心會回收。
- foreach ($cmdArr as $cmd) {
- $pid = pcntl_fork(); //建立子進程
- //父進程和子進程都會執行下面代碼
- if ($pid == -1) {
- //錯誤處理:建立子進程失敗時返回-1.
- die(‘could not fork‘);
- } else if ($pid) {
- //父進程會得到子進程號,所以這裡是父進程執行的邏輯
- //如果不需要阻塞進程,而又想得到子進程的退出狀態,則可以注釋掉pcntl_wait($status)語句,或寫成:
- pcntl_wait($status,WNOHANG); //等待子進程中斷,防止子進程成為殭屍進程。
- } else {
- //子進程得到的$pid為0, 所以這裡是子進程執行的邏輯。
- $path = $cmd["path"];
- $pid = $cmd[‘pid‘] ;
- $total = $cmd[‘total‘] ;
- echo exec("/usr/bin/php {$path} {$pid} {$total}")."\n";
- exit(0) ;
- }
- }
- ?>
PHP多進程實現