具體代碼如下所示:
?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)注明出處,謝謝!
標(biāo)簽:湘西 海北 梅河口 惠州 濮陽(yáng) 黔東 文山 廈門(mén)
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《php實(shí)現(xiàn) master-worker 守護(hù)多進(jìn)程模式的實(shí)例代碼》,本文關(guān)鍵詞 php,實(shí)現(xiàn),master-worker,守護(hù),;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。