PHP基于進程控制函數實現多線程
php有一組進程控制函數(編譯時需要?enable-pcntl與posix擴展),使得php能在nginx系統中實現跟c一樣的創建子進程、使用exec函數執行程序、處理信號等功能。
CentOS 6 下yum安裝php的,默認是不安裝pcntl的,因此需要單獨編譯安裝,首先下載對應版本的php,解壓后
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 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) ; } } ?>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
