PHP flock() alternative

后端 未结 7 1788
一个人的身影
一个人的身影 2020-12-09 11:40

PHP\'s documentation page for flock() indicates that it\'s not safe to use under IIS. If I can\'t rely on flock under all circumstances, is there another way I

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-09 11:49

    Based on mkdir:

    // call this always before reading or writing to your filepath in concurrent situations
    function lockFile($filepath){
       clearstatcache();
       $lockname=$filepath.".lock";
       // if the lock already exists, get its age:
       $life=@filectime($lockname);
       // attempt to lock, this is the really important atomic action:
       while (!@mkdir($lockname)){
         if ($life)
            if ((time()-$life)>120){
               //release old locks
               rmdir($lockname);
         }else $life=@filectime($lockname);
         usleep(rand(50000,200000));//wait random time before trying again
       }
    }
    

    To avoid deadlock when one script in case a script exits before it has unlocked and one (or more scripts) at the same time have no result on $life=@filectime($lockname); because all scripts starts at the same time and then directory isn't created yet. To unlock then call:

    function unlockFile($filepath){
       $unlockname= $filepath.".lock";   
      return @rmdir($unlockname);
    }
    

提交回复
热议问题