开发者

Issue with flock when running script in cron job

I am using the following code:

$fp = fopen("lock.txt", "w");
if (flock($fp, LOCK_EX|LOCK_NB)) { // do an exclusive lock
    //Do something here.
}else{
   echo "Could not lock file!";
}

This code runs fine when I run my script from my browser (it locks and I can only run it once) but when running it via cron job, the lock.txt file isn't even created. I am a little stumped as I presume the Cron runs as the same user that runs the browser version so it obviously has permissions.

Anyone else had something like this?

EDIT:开发者_开发百科 Ok the file is created now I have done specific paths to the directory. However, the file is overwritten everytime the cron starts an isn't actually locking the file.


This is the correct way to do that.

<?php
$tempDir = sys_get_temp_dir() . "/";
$fp = fopen("$tempDirlock.txt", "r+");

if (flock($fp, LOCK_EX | LOCK_NB)) { // do an exclusive lock
    // do the work

    flock($fp, LOCK_UN); // release the lock
} else {
    echo "Couldn't get the lock!";
}

fclose($fp);
?>


why not use fwrite to overwrite the lock file contents with time() and when your script is finished clear the file.

you can check if the script is running and for how long.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜