PHP守护进程

php也是可以直接进行守护进程的启动与终止的,相对于shell来说会简单很多,理解更方便,当然了php的守护进程要实现自动重启还是要依赖于shell的crontab日程表,每隔一段时间去执行一次脚本看脚本是否需要重启,如果需要则杀掉进程删除RunFile文件,重新启动并在RunFile文件中写入pid。

复制代码
<?php       
function start($file){
    $path = dirname(__FILE__).'/';
    $runfile = $path.$file.'.run';
    $diefile = $path.$file.'.die';
    $file = $path."data/{$file}.php";
    clearstatcache();
    if(file_exists($runfile)){
        $oldpid = file_get_contents($runfile);
        $nowpid = shell_exec("ps aux | grep 'php -f process.php' | grep ${oldpid} | awk '{print $2}'");
        //如果runfile中的pid号可以匹配到正在运行的,并且上次访问runfile的时间和现在相差小于5min则返回
        if(($oldpid == $nowpid) && (time() - fileatime($runfile) < 300)){
            echo "$file is circle runing no";
            return;
        }else{
            //pid号不匹配或者已经有300秒没有运行循环语句,直接杀掉进程,重新启动
            $pid = file_get_contents($runfile);
            shell_exec("ps aux | grep 'php -f process.php' | grep {$pid} | xargs --if-no-run-empty kill");
        }
    }else{
        //将文件pid写入run文件
        if(!($newpid = getmypid()) || !file_put_contents($runfile,$newpid)){
            return;
        }
        while(true){
            //收到结束进程新号,结束进程,并删除相关文件
            if(file_exists($diefile) && unlink($runfile) && unlink($diefile)){
                return;
            }
            /*这里是守护进程要做的事*/
            file_put_contents($file,"I'm Runing Now".PHP_EOL,FILE_APPEND);
            /***********************/
            touch($runfile);
            sleep(5);
        }
    }
}
start("test");
复制代码

php写守护进程时童谣要注意几点:

crontab -e
#打开日程表,inset模式

*/3 * * * * /usr/bin/php -f process.php
#每3分钟执行一次,放置进程挂掉

这样就基本ok了,要是有具体功能的话还需改动代码。

send me~

posted @   奔跑的Man  阅读(2162)  评论(1编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述
点击右上角即可分享
微信分享提示