简体   繁体   中英

How to limit 1 instance of a PHP script, what's wrong with my solution

<?PHP
define('TEMPPATH', '/tmp/');
$fp = fopen(TEMPPATH.'abc.php.lock', 'a+');
if(!flock($fp, LOCK_EX | LOCK_NB))
    exit;

I use the above codes to limit the script from running multiple instances, and it's OK when I test it, but today when I logged in to my server (CentOS 6) and I saw two instances running, how could that happen?

[root@server user]# ps aux | grep abc
root     21061  0.0  0.1 103284  2016 pts/0    S+   15:45   0:00 grep abc
user     22560  0.0  1.2 154608 12788 ?        Ss   Nov10   1:35 /usr/bin/php /path/abc.php
user     25106  0.0  1.3 154896 13336 ?        Ss   Nov06   2:51 /usr/bin/php /path/abc.php

The script was started from crontab jobs, crontab tries to run it every minute, is there any better ways to do this ?

Very elaborate instance control :).

Take a look at mine:

function par_processes($name = null,$ownPids = array(),$dbg = false){
    exec("ps x | grep $name", $ProcessState);
    $modifier = 0;

    while (list($idp,$procs) = each($ProcessState)){
        if (preg_match("/grep/i",$procs)) {
            unset($ProcessState[$idp]);
        }else{
            if (!empty($ownPids)){
                if (in_array(strstr(trim($procs)," ",true),$ownPids)){
                    unset($ProcessState[$idp]);
                }
            }
        }
    }

    if (!$dbg){
        return (count($ProcessState) - $modifier);
    }else{
        return array(0=>(count($ProcessState) - $modifier),1=>$ProcessState,2=>$ownPids);
    }
}

And in the php daemon before I go any further I use this:

# INSTANCE CHECK    
if (par_processes("MYSOFTWARENAME",array(getmypid()))){
    error_log("SOME ERROR"); die();
}

Quite frankly it can be done quicker and more effective (probably) but it does the job. Of course you need to be able to run exec() for this to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM