温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

怎么在php中利用master-worker 实现守护多进程模式

发布时间:2021-05-26 12:44:23 来源:亿速云 阅读:161 作者:Leah 栏目:开发技术

本篇文章给大家分享的是有关怎么在php中利用master-worker 实现守护多进程模式,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

具体代码如下所示:

<?php
class Worker{
  public static $count = 2;
  public static function runAll(){
    static::runMaster();
    static::moniProcess();
  }
  //开启主进程
  public static function runMaster(){
    //确保进程有最大操作权限
    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("创建主进程失败");
    }
  } 
  //开启子进程
  public static function runWorker(){
    unmask(0);
    $pid = pcntl_fork();
    if($pid > 0){
      // echo "创建子进程 $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("创建子进程失败");
    }
  }
  //监控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

执行命令 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

以上就是怎么在php中利用master-worker 实现守护多进程模式,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI