• PHP进程实现方式之死循环(一)


    今天整理一点PHP原生实现进程的方式,死循环。针对进程一般要借助于定时去检查进程的重启与销毁,也可以依赖于文件,或者配置自我实现重启。

    而php一般的死循环实现方式如下:

      

     1 function doAnalisis($param1,$param2){
     2     $runFile = ROOT_PATH."Log/runprocess/player{$param1}.{$param2}.run";
     3     $dieFile = ROOT_PATH."Log/runprocess/player{$param1}.{$param2}.die";
     4     clearstatcache(); // 清除文件缓存,不然获取最后访问时间会出错
     5     //判断是否需要重启
     6     if(file_exists($runFile)){
     7         //重启检测设为300s,当300s中未对runFile进行访问时,重启进程
     8         if(time() - fileatime($runFile) < 300){
     9             return;
    10         }else{
    11             $pid = file_get_contents($runFile);
    12             shell_exec("ps aux | grep '{$_SERVER['PHP_SELF']}' | grep 'Cms/Process/playAnalisis/roomid/{$param1}&pNum={$param2}' | grep -v 'grep' | awk '{print $2}' | grep {$pid} | xargs --no-run-if-empty kill");
    13         }
    14     }
    15 
    16     //启动进程
    17     if(!file_put_contents($runFile, getmypid())){
    18         return;
    19     }
    20     //处理牌局
    21     while (true) {
    22         //检查重启
    23         if(file_exists($dieFile)){
    24             unlink($runFile) && unlink($dieFile);
    25             return;
    26         }
    27         //更新文件修改时间
    28         
    29         touch($runFile);
    30         //从缓存或者从其它地方获取数据来源
    31         $data = [];
    32         
    33         if( empty($data) ){
    34             sleep(1);
    35             continue;
    36         }
    37         
    38         //业务逻辑处理
    39         foreach($data as $gamb) {
    40             
    41         }
    42     }
    43 }

       说明:

      通过while touch不断的修改文件的修改时间来确保进程的运行态。

      通过检查run文件的修改时间来判断进程是否不存在需要重启 。

      可以根据传递的参数启动多个进程对数据进行处理。

    PHP中常见的问题点,知识点,及盲点。
  • 相关阅读:
    Codeforces 1131 C. Birthday-暴力 (Codeforces Round #541 (Div. 2))
    Codeforces 1131 B. Draw!-暴力 (Codeforces Round #541 (Div. 2))
    DP之背包经典三例
    博弈规律综概
    腾讯面试题:杯子质量(最优查找)
    洛谷P1308——单词统计
    AtCoder Regular Contest 069 D
    Codeforces 782C. Andryusha and Colored Balloons 搜索
    Codeforces 799D. String Game 二分
    Codeforces 767B. The Queue 模拟题
  • 原文地址:https://www.cnblogs.com/sblack/p/12911194.html
Copyright © 2020-2023  润新知