php多进程实现 亲测
生活随笔
收集整理的這篇文章主要介紹了
php多进程实现 亲测
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
php多進(jìn)程實(shí)現(xiàn)
PHP有一組進(jìn)程控制函數(shù)(編譯時(shí)需要–enable-pcntl與posix擴(kuò)展),使得php能在nginx系統(tǒng)中實(shí)現(xiàn)跟c一樣的創(chuàng)建子進(jìn)程、使用exec函數(shù)執(zhí)行程序、處理信號等功能。
CentOS 6 下yum安裝php的,默認(rèn)是不安裝pcntl的,因此需要單獨(dú)編譯安裝,首先下載對應(yīng)版本的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 // 必須加載擴(kuò)展 5 if (!function_exists("pcntl_fork")) { 6 die("pcntl extention is must !"); 7 } 8 //總進(jìn)程的數(shù)量 9 $totals = 3; 10 // 執(zhí)行的腳本數(shù)量 11 $cmdArr = array(); 12 // 執(zhí)行的腳本數(shù)量的數(shù)組 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); //如果父進(jìn)程不關(guān)心子進(jìn)程什么時(shí)候結(jié)束,子進(jìn)程結(jié)束后,內(nèi)核會(huì)回收。 46 foreach ($cmdArr as $cmd) { 47 $pid = pcntl_fork(); //創(chuàng)建子進(jìn)程 48 //父進(jìn)程和子進(jìn)程都會(huì)執(zhí)行下面代碼 49 if ($pid == -1) { 50 //錯(cuò)誤處理:創(chuàng)建子進(jìn)程失敗時(shí)返回-1. 51 die('could not fork'); 52 } else if ($pid) { 53 //父進(jìn)程會(huì)得到子進(jìn)程號,所以這里是父進(jìn)程執(zhí)行的邏輯 54 //如果不需要阻塞進(jìn)程,而又想得到子進(jìn)程的退出狀態(tài),則可以注釋掉pcntl_wait($status)語句,或?qū)懗?#xff1a; 55 pcntl_wait($status,WNOHANG); //等待子進(jìn)程中斷,防止子進(jìn)程成為僵尸進(jìn)程。 56 } else { 57 //子進(jìn)程得到的$pid為0, 所以這里是子進(jìn)程執(zhí)行的邏輯。 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 ?>?
轉(zhuǎn)載于:https://www.cnblogs.com/easirm/p/4189896.html
總結(jié)
以上是生活随笔為你收集整理的php多进程实现 亲测的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows中用运行命令直接启动指定软
- 下一篇: php 表单校验函数库(判断email格