swoole_process,子进程自动重启及主进程退出后,子进程退出的试例.


 1 1.子进程异常退出后,自动重启子进程, 2. 主进程异常退出后,子进程在干完当前工作后,自动退出
 2 
 3 (new class{
 4     public $mpid=0;
 5     public $works=[];
 6     public $max_precess=1;
 7     public $new_index=0;
 8 
 9     public function __construct(){
10         try {
11             swoole_set_process_name(sprintf('php-ps:%s', 'master'));
12             $this->mpid = posix_getpid();
13             $this->run();
14             $this->processWait();
15         }catch (\Exception $e){
16             die('ALL ERROR: '.$e->getMessage());
17         }
18     }
19 
20     public function run(){
21         for ($i=0; $i < $this->max_precess; $i++) {
22             $this->CreateProcess();
23         }
24     }
25 
26     public function CreateProcess($index=null){
27         $process = new swoole_process(function(swoole_process $worker)use($index){
28             if(is_null($index)){
29                 $index=$this->new_index;
30                 $this->new_index++;
31             }
32             swoole_set_process_name(sprintf('php-ps:%s',$index));
33             for ($j = 0; $j < 16000; $j++) {
34                 $this->checkMpid($worker);
35                 echo "msg: {$j}\n";
36                 sleep(1);
37             }
38         }, false, false);
39         $pid=$process->start();
40         $this->works[$index]=$pid;
41         return $pid;
42     }
43     public function checkMpid(&$worker){
44         if(!swoole_process::kill($this->mpid,0)){
45             $worker->exit();
46             // 这句提示,实际是看不到的.需要写到日志中
47             echo "Master process exited, I [{$worker['pid']}] also quit\n";
48         }
49     }
50 
51     public function rebootProcess($ret){
52         $pid=$ret['pid'];
53         $index=array_search($pid, $this->works);
54         if($index!==false){
55             $index=intval($index);
56             $new_pid=$this->CreateProcess($index);
57             echo "rebootProcess: {$index}={$new_pid} Done\n";
58             return;
59         }
60         throw new \Exception('rebootProcess Error: no pid');
61     }
62 
63     public function processWait(){
64         while(1) {
65             if(count($this->works)){
66                 $ret = swoole_process::wait();
67                 if ($ret) {
68                     $this->rebootProcess($ret);
69                 }
70             }else{
71                 break;
72             }
73         }
74     }
75 });

优质内容筛选与推荐>>
1、[快学Python3]Sets(集合)
2、【译】谷歌谋杀了圣诞老人?
3、Redis实现信息已读未读状态提示
4、内网软件设计要领
5、[nptl][rwlock]pthreadrwlock原理分析


长按二维码向我转账

受苹果公司新规定影响,微信 iOS 版的赞赏功能被关闭,可通过二维码转账支持公众号。

    阅读
    好看
    已推荐到看一看
    你的朋友可以在“发现”-“看一看”看到你认为好看的文章。
    已取消,“好看”想法已同步删除
    已推荐到看一看 和朋友分享想法
    最多200字,当前共 发送

    已发送

    朋友将在看一看看到

    确定
    分享你的想法...
    取消

    分享想法到看一看

    确定
    最多200字,当前共

    发送中

    网络异常,请稍后重试

    微信扫一扫
    关注该公众号