php實現(xiàn) master-worker 守護多進程模式的實例代碼
更新時間:2019年07月20日 09:47:25 作者:碼緣
這篇文章主要介紹了php實現(xiàn) master-worker 守護多進程模式的實例代碼,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值 ,需要的朋友可以參考下
具體代碼如下所示:
<?php
class Worker{
public static $count = 2;
public static function runAll(){
static::runMaster();
static::moniProcess();
}
//開啟主進程
public static function runMaster(){
//確保進程有最大操作權(quán)限
unmask(0);
$pid = pcntl_fork();
if($pid > 0){
echo "主進程進程 $pid \n";
exit;
}else if($pid == 0){
if(-1 === posix_setsid()){
throw new Exception("setsid fail");
}
for ($i=0; $i < self::$count; $i++) {
static::runWorker();
}
@cli_set_process_title("master_process");
}else{
throw new Exception("創(chuàng)建主進程失敗");
}
}
//開啟子進程
public static function runWorker(){
unmask(0);
$pid = pcntl_fork();
if($pid > 0){
// echo "創(chuàng)建子進程 $pid \n";
}else if($pid == 0){
if(-1 === posix_setsid()){
throw new Exception("setsid fail");
}
@cli_set_process_title("worker_process");
while(1){
sleep(1);
}
}else{
throw new Exception("創(chuàng)建子進程失敗");
}
}
//監(jiān)控worker進程
public function moniProcess(){
while( $pid = pcntl_wait($status)){
if($pid == -1){
break;
}else{
static::runWorker();
}
}
}
}
Worker::runAll();
ps -aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 18200 3076 pts/0 Ss+ 14:05 0:00 bash root 6 0.0 0.0 18208 3252 pts/1 Ss 14:06 0:00 bash root 19 0.0 0.0 18204 3248 pts/2 Ss+ 14:11 0:00 bash root 64 0.0 0.2 348488 8320 ? Ss 15:32 0:00 master_process root 65 0.0 0.2 348488 8400 ? Ss 15:32 0:00 worker_process root 66 0.0 0.2 348488 8400 ? Ss 15:32 0:00 worker_process root 67 0.0 0.0 36640 2804 pts/1 R+ 15:32 0:00 ps -aux
執(zhí)行命令 kill 65,殺死進程 65 則master_process 進程會再自動開啟一個子進程
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.0 18200 3076 pts/0 Ss+ 14:05 0:00 bash root 6 0.0 0.0 18208 3252 pts/1 Ss 14:06 0:00 bash root 19 0.0 0.0 18204 3248 pts/2 Ss+ 14:11 0:00 bash root 64 0.0 0.2 348488 8320 ? Ss 15:32 0:00 master_process root 66 0.0 0.2 348488 8400 ? Ss 15:32 0:00 worker_process root 68 0.0 0.1 348488 5796 ? Ss 15:34 0:00 worker_process root 69 0.0 0.0 36640 2728 pts/1 R+ 15:34 0:00 ps -aux
總結(jié)
以上所述是小編給大家介紹的php實現(xiàn) master-worker 守護多進程模式的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
相關(guān)文章
php 使用mpdf實現(xiàn)指定字段配置字體樣式的方法
前兩天在做一個pdf導出功能,使用的插件是kartik-v/yii2-mpdf,此插件使用的是mpdf。接下來通過本文給大家介紹php 使用mpdf實現(xiàn)指定字段配置字體樣式的方法,需要的朋友可以參考下2019-07-07

