php实现 master-worker 守护多进程模式的实例代码

这篇文章主要介绍了php实现 master-worker 守护多进程模式的实例代码,代码简单易懂,非常不错,具有一定的参考借鉴价值 ,需要的朋友可以参考下。

具体代码如下所示:

  1. <?php
  2. class Worker{
  3. public static $count = 2;
  4. public static function runAll(){
  5. static::runMaster();
  6. static::moniProcess();
  7. }
  8. //开启主进程
  9. public static function runMaster(){
  10. //确保进程有最大操作权限
  11. unmask(0);
  12. $pid = pcntl_fork();
  13. if($pid > 0){
  14. echo "主进程进程 $pid \n";
  15. exit;
  16. }else if($pid == 0){
  17. if(-1 === posix_setsid()){
  18. throw new Exception("setsid fail");
  19. }
  20. for ($i=0; $i < self::$count; $i++) {
  21. static::runWorker();
  22. }
  23. @cli_set_process_title("master_process");
  24. }else{
  25. throw new Exception("创建主进程失败");
  26. }
  27. }
  28. //开启子进程
  29. public static function runWorker(){
  30. unmask(0);
  31. $pid = pcntl_fork();
  32. if($pid > 0){
  33. // echo "创建子进程 $pid \n";
  34. }else if($pid == 0){
  35. if(-1 === posix_setsid()){
  36. throw new Exception("setsid fail");
  37. }
  38. @cli_set_process_title("worker_process");
  39. while(1){
  40. sleep(1);
  41. }
  42. }else{
  43. throw new Exception("创建子进程失败");
  44. }
  45. }
  46. //监控worker进程
  47. public function moniProcess(){
  48. while( $pid = pcntl_wait($status)){
  49. if($pid == -1){
  50. break;
  51. }else{
  52. static::runWorker();
  53. }
  54. }
  55. }
  56. }

Worker::runAll();

  1. ps -aux
  2. USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
  3. root 1 0.0 0.0 18200 3076 pts/0 Ss+ 14:05 0:00 bash
  4. root 6 0.0 0.0 18208 3252 pts/1 Ss 14:06 0:00 bash
  5. root 19 0.0 0.0 18204 3248 pts/2 Ss+ 14:11 0:00 bash
  6. root 64 0.0 0.2 348488 8320 ? Ss 15:32 0:00 master_process
  7. root 65 0.0 0.2 348488 8400 ? Ss 15:32 0:00 worker_process
  8. root 66 0.0 0.2 348488 8400 ? Ss 15:32 0:00 worker_process
  9. root 67 0.0 0.0 36640 2804 pts/1 R+ 15:32 0:00 ps -aux

执行命令 kill 65,杀死进程 65 则master_process 进程会再自动开启一个子进程

  1. USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
  2. root 1 0.0 0.0 18200 3076 pts/0 Ss+ 14:05 0:00 bash
  3. root 6 0.0 0.0 18208 3252 pts/1 Ss 14:06 0:00 bash
  4. root 19 0.0 0.0 18204 3248 pts/2 Ss+ 14:11 0:00 bash
  5. root 64 0.0 0.2 348488 8320 ? Ss 15:32 0:00 master_process
  6. root 66 0.0 0.2 348488 8400 ? Ss 15:32 0:00 worker_process
  7. root 68 0.0 0.1 348488 5796 ? Ss 15:34 0:00 worker_process
  8. root 69 0.0 0.0 36640 2728 pts/1 R+ 15:34 0:00 ps -aux