首页 > 语言 > JavaScript > 正文

PHP守护进程实例

2024-05-06 14:44:57
字体:
来源:转载
供稿:网友

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);

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选