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

2025-05-29 0 66

具体代码如下所示:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57
<?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();

?

1

2

3

4

5

6

7

8

9
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 进程会再自动开启一个子进程

?

1

2

3

4

5

6

7

8
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 守护多进程模式的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对快网idc网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

原文链接:https://www.cnblogs.com/itsuibi/archive/2019/07/20/11189234.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 php实现 master-worker 守护多进程模式的实例代码 https://www.kuaiidc.com/92428.html

相关文章

发表评论
暂无评论