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í)行程序、處理信號(hào)等功能。
CentOS 6 下yum安裝php的,默認(rèn)是不安裝pcntl的,因此需要單獨(dú)編譯安裝,首先下載對(duì)應(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)核會(huì)回收。 foreach ($cmdArr as $cmd) { $pid = pcntl_fork(); //創(chuàng)建子進(jìn)程 //父進(jìn)程和子進(jìn)程都會(huì)執(zhí)行下面代碼 if ($pid == -1) { //錯(cuò)誤處理:創(chuàng)建子進(jìn)程失敗時(shí)返回-1. die(’could not fork’); } else if ($pid) { //父進(jìn)程會(huì)得到子進(jìn)程號(hào),所以這里是父進(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) ; } } ?>
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. Python獲取抖音關(guān)注列表封號(hào)賬號(hào)的實(shí)現(xiàn)代碼2. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報(bào)錯(cuò)問題分析3. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究4. 解決Python 進(jìn)程池Pool中一些坑5. php測(cè)試程序運(yùn)行速度和頁面執(zhí)行速度的代碼6. Python如何讀寫CSV文件7. 三個(gè)不常見的 HTML5 實(shí)用新特性簡(jiǎn)介8. ajax請(qǐng)求添加自定義header參數(shù)代碼9. python利用os模塊編寫文件復(fù)制功能——copy()函數(shù)用法10. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁
