Home  >  Article  >  Backend Development  >  Will php infinite loop report an error?

Will php infinite loop report an error?

藏色散人
藏色散人Original
2023-01-18 11:09:221372browse

php死循环不会报错;死循环是指无法靠自身的控制终止的循环,在编程中,指一个靠自身控制无法终止的程序;而死循环不是错误,因为程序就是要它一直循环下去;如果死循环编译报错,停止编译,那么需要死循环的程序就没办法实现。

Will php infinite loop report an error?

本教程操作环境:Windows10系统、PHP8.1版、DELL G3电脑

php死循环会报错吗?

不会报错。

死循环不是错误,因为有些程序就是要它一直循环下去--“死循环”,需要结束时, Ctrl+C。

如果死循环编译报错,停止编译,那么需要死循环的程序就没办法实现了。

相关介绍:

死循环(endless loop)是指无法靠自身的控制终止的循环,在编程中,一个靠自身控制无法终止的程序。

例如:

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

 function doAnalisis($param1,$param2){
     $runFile = ROOT_PATH."Log/runprocess/player{$param1}.{$param2}.run";
     $dieFile = ROOT_PATH."Log/runprocess/player{$param1}.{$param2}.die";
     clearstatcache(); // 清除文件缓存,不然获取最后访问时间会出错
     //判断是否需要重启
     if(file_exists($runFile)){
         //重启检测设为300s,当300s中未对runFile进行访问时,重启进程
         if(time() - fileatime($runFile) < 300){
             return;
         }else{
             $pid = file_get_contents($runFile);
             shell_exec("ps aux | grep &#39;{$_SERVER[&#39;PHP_SELF&#39;]}&#39; | grep &#39;Cms/Process/playAnalisis/roomid/{$param1}&pNum={$param2}&#39; | grep -v &#39;grep&#39; | awk &#39;{print $2}&#39; | grep {$pid} | xargs --no-run-if-empty kill");
         }
     }
 
     //启动进程
     if(!file_put_contents($runFile, getmypid())){
         return;
     }
     //处理牌局
     while (true) {
         //检查重启
         if(file_exists($dieFile)){
             unlink($runFile) && unlink($dieFile);
             return;
         }
         //更新文件修改时间
         
         touch($runFile);
         //从缓存或者从其它地方获取数据来源
         $data = [];
         
         if( empty($data) ){
             sleep(1);
             continue;
         }
         
         //业务逻辑处理
         foreach($data as $gamb) {
             
         }
     }
 }

   说明:

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

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

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

推荐学习:《PHP视频教程

The above is the detailed content of Will php infinite loop report an error?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn