简体   繁体   中英

PHP: How can I check wether or not a php script is already running?

I'm using a php script to read emails recieved by my application's bounce address and do stuff with them. The script is scheduled to run with cron jobs but I have no control over it and I don't have permission to write files on the server (so that pretty much eliminates the file locking mechanism). Is there another way to ensure I have only one instance of the script running at any given time? The server is running linux.

I suppose you could try this:

// we use ourselves as the lock file
if (false === ($f = fopen(__FILE__, 'r'))) {
    die("Could not open lock file");
}
if (false === flock($f, LOCK_EX)) {
    die("Could not obtain lock");
}
// do your stuff
flock($f, LOCK_UN);
fclose($f);

You don't need write access to work with advisory locks; this is of course assuming that flock() is enabled in your configuration.

its a little bit dirty but

if(file_exists("block.bin")) {
  //already running
}

file_put_contents("block.bin", 1);

 //do stuff

unlink("block.bin");

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