php Implementation of master worker Daemon Multi process Mode Instance Code
- 2021-12-13 07:33:10
- OfStack
The specific code is as follows:
<?php
class Worker{
public static $count = 2;
public static function runAll(){
static::runMaster();
static::moniProcess();
}
// Start the main process
public static function runMaster(){
// Ensure that the process has maximum operation permissions
unmask(0);
$pid = pcntl_fork();
if($pid > 0){
echo " Main process process $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(" Failed to create main process ");
}
}
// Start a child process
public static function runWorker(){
unmask(0);
$pid = pcntl_fork();
if($pid > 0){
// echo " Create a child process $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(" Failed to create child process ");
}
}
// Monitoring worker Process
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
Execute the command kill 65, kill the process 65 and the master_process process will automatically start another child 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
Summarize