PHP基于進(jìn)程控制函數(shù)實(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,解壓后
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’ ); // 必須加載擴(kuò)展 if (!function_exists('pcntl_fork')) { die('pcntl extention is must !'); } //總進(jìn)程的數(shù)量 $totals = 3; // 執(zhí)行的腳本數(shù)量 $cmdArr = array(); // 執(zhí)行的腳本數(shù)量的數(shù)組 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); //如果父進(jìn)程不關(guān)心子進(jìn)程什么時(shí)候結(jié)束,子進(jìn)程結(jié)束后,內(nèi)核會回收。 foreach ($cmdArr as $cmd) { $pid = pcntl_fork(); //創(chuàng)建子進(jìn)程 //父進(jìn)程和子進(jìn)程都會執(zhí)行下面代碼 if ($pid == -1) { //錯(cuò)誤處理:創(chuàng)建子進(jìn)程失敗時(shí)返回-1. die(’could not fork’); } else if ($pid) { //父進(jìn)程會得到子進(jìn)程號,所以這里是父進(jìn)程執(zhí)行的邏輯 //如果不需要阻塞進(jìn)程,而又想得到子進(jìn)程的退出狀態(tài),則可以注釋掉pcntl_wait($status)語句,或?qū)懗桑? pcntl_wait($status,WNOHANG); //等待子進(jìn)程中斷,防止子進(jìn)程成為僵尸進(jìn)程。 } else { //子進(jìn)程得到的$pid為0, 所以這里是子進(jìn)程執(zhí)行的邏輯。 $path = $cmd['path']; $pid = $cmd[’pid’] ; $total = $cmd[’total’] ; echo exec('/usr/bin/php {$path} {$pid} {$total}').'n'; exit(0) ; } } ?>
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 詳解Android studio 動態(tài)fragment的用法2. 編程語言PHP在Web開發(fā)領(lǐng)域的優(yōu)勢在哪?3. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)4. 什么是python的自省5. 解決Android studio xml界面無法預(yù)覽問題6. Android如何加載Base64編碼格式圖片7. 基于android studio的layout的xml文件的創(chuàng)建方式8. Springboot Druid 自定義加密數(shù)據(jù)庫密碼的幾種方案9. 圖文詳解vue中proto文件的函數(shù)調(diào)用10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備