具體代碼如下所示:
?php
class Worker{
public static $count = 2;
public static function runAll(){
static::runMaster();
static::moniProcess();
}
//開(kāi)啟主進(jìn)程
public static function runMaster(){
//確保進(jìn)程有最大操作權(quán)限
unmask(0);
$pid = pcntl_fork();
if($pid > 0){
echo "主進(jìn)程進(jìn)程 $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)建主進(jìn)程失敗");
}
}
//開(kāi)啟子進(jìn)程
public static function runWorker(){
unmask(0);
$pid = pcntl_fork();
if($pid > 0){
// echo "創(chuàng)建子進(jìn)程 $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)建子進(jìn)程失敗");
}
}
//監(jiān)控worker進(jìn)程
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,殺死進(jìn)程 65 則master_process 進(jìn)程會(huì)再自動(dòng)開(kāi)啟一個(gè)子進(jìn)程
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實(shí)現(xiàn) master-worker 守護(hù)多進(jìn)程模式的實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺(jué)得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
您可能感興趣的文章:- PHP守護(hù)進(jìn)程化在C和PHP環(huán)境下的實(shí)現(xiàn)
- PHP守護(hù)進(jìn)程的兩種常見(jiàn)實(shí)現(xiàn)方式詳解
- php腳本守護(hù)進(jìn)程原理與實(shí)現(xiàn)方法詳解
- PHP程序員玩轉(zhuǎn)Linux系列 使用supervisor實(shí)現(xiàn)守護(hù)進(jìn)程
- PHP高級(jí)編程實(shí)例:編寫(xiě)守護(hù)進(jìn)程
- shell腳本作為保證PHP腳本不掛掉的守護(hù)進(jìn)程實(shí)例分享
- php守護(hù)進(jìn)程 加linux命令nohup實(shí)現(xiàn)任務(wù)每秒執(zhí)行一次
- PHP程序守護(hù)進(jìn)程化實(shí)現(xiàn)方法詳解