php多进程实现 亲测
生活随笔
收集整理的這篇文章主要介紹了
php多进程实现 亲测
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
php多進程實現
PHP有一組進程控制函數(編譯時需要–enable-pcntl與posix擴展),使得php能在nginx系統中實現跟c一樣的創建子進程、使用exec函數執行程序、處理信號等功能。
CentOS 6 下yum安裝php的,默認是不安裝pcntl的,因此需要單獨編譯安裝,首先下載對應版本的php,解壓后
1 cd php-version/ext/pcntl 2 phpize 3 ./configure && make && make install 4 cp /usr/lib/php/modules/pcntl.so /usr/lib64/php/modules/pcntl.so 5 echo "extension=pcntl.so" >> /etc/php.ini 6 /etc/init.d/httpd restart方便極了。
下面是示例代碼:
1 <?php 2 header('content-type:text/html;charset=utf-8' ); 3 4 // 必須加載擴展 5 if (!function_exists("pcntl_fork")) { 6 die("pcntl extention is must !"); 7 } 8 //總進程的數量 9 $totals = 3; 10 // 執行的腳本數量 11 $cmdArr = array(); 12 // 執行的腳本數量的數組 13 for ($i = 0; $i < $totals; $i++) { 14 $cmdArr[] = array("path" => __DIR__ . "/run.php", 'pid' =>$i ,'total' =>$totals); 15 } 16 17 /* 18 展開:$cmdArr 19 Array 20 ( 21 [0] => Array 22 ( 23 [path] => /var/www/html/company/pcntl/run.php 24 [pid] => 0 25 [total] => 3 26 ) 27 28 [1] => Array 29 ( 30 [path] => /var/www/html/company/pcntl/run.php 31 [pid] => 1 32 [total] => 3 33 ) 34 35 [2] => Array 36 ( 37 [path] => /var/www/html/company/pcntl/run.php 38 [pid] => 2 39 [total] => 3 40 ) 41 42 ) 43 */ 44 45 pcntl_signal(SIGCHLD, SIG_IGN); //如果父進程不關心子進程什么時候結束,子進程結束后,內核會回收。 46 foreach ($cmdArr as $cmd) { 47 $pid = pcntl_fork(); //創建子進程 48 //父進程和子進程都會執行下面代碼 49 if ($pid == -1) { 50 //錯誤處理:創建子進程失敗時返回-1. 51 die('could not fork'); 52 } else if ($pid) { 53 //父進程會得到子進程號,所以這里是父進程執行的邏輯 54 //如果不需要阻塞進程,而又想得到子進程的退出狀態,則可以注釋掉pcntl_wait($status)語句,或寫成: 55 pcntl_wait($status,WNOHANG); //等待子進程中斷,防止子進程成為僵尸進程。 56 } else { 57 //子進程得到的$pid為0, 所以這里是子進程執行的邏輯。 58 $path = $cmd["path"]; 59 $pid = $cmd['pid'] ; 60 $total = $cmd['total'] ; 61 echo exec("/usr/bin/php {$path} {$pid} {$total}")."\n"; 62 exit(0) ; 63 } 64 } 65 ?>?
轉載于:https://www.cnblogs.com/easirm/p/4189896.html
總結
以上是生活随笔為你收集整理的php多进程实现 亲测的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows中用运行命令直接启动指定软
- 下一篇: 读书笔记_java设计模式深入研究 第八