2009/04/20

Linux下PHP保持进程唯一运行


<?php

//确认进程唯一,防止死掉
function check_proc() {
    if( $pidfile = @file_get_contents("./my.pid") )
    {
        list($pid, $last_time) = explode(",", $pidfile);       
        if( $link = @readlink("/proc/{$pid}/exe") )
        {
            if( time()-$last_time > 60*60 )//1 hour
            {
                //超时KILL掉那个进程
                system("kill -9 {$pid}");
            }else{
                echo "already exist, process exit.\n";
                exit;
            }
        }
    }
    //写入当前PID信息
    file_put_contents("./my.pid", getmypid().','.time() );
}

?>


getmypid()获取进程的ID。

在PHP程序起始处运行此函数,即可确保进程唯一,且可以踢掉超时的进程。

也可以使用shell_exec("ps aux|grep ".$pid)来判断进程是否存在。对Linux越熟悉就越多方法。

没有评论:

发表评论