search
Homephp教程php手册模拟flock实现文件锁定

模拟flock实现文件锁定

Jun 13, 2016 pm 12:34 PM
flockmainandaccomplishIdeassupplydocumentsimulationLocklocking

主要提供了一种思路。
  $lock0和$lock1就是文件锁定的标识符,当文件被某一用户打开的时候,$lock0和$lock1就会产生,当该文件没打开则不存在。
  其实最关键就是有个标识符来表示当前这个文件的状态, $lock0和$lock1就是起这样的作用。

复制代码 代码如下:



// Lock a file, timing out if it takes too long.  
function lock ($lock, $tries) {  
       $lock0 = ".{$lock}0";  
       $lock1 = ".{$lock}1";  
       for ($i=0; $i               if (!is_file($lock0)) {  
                       touch($lock0);  
                       if (!is_file($lock1)) {  
                               touch($lock1);  
                               return 1;  
                       }  
               }  
               usleep(100);  
       }  
       return 0;  
}  

// Unlock a file.  
function unlock ($lock) {  
       unlink(".{$lock}1");  
       unlink(".{$lock}0");  
}  

// Usage example.  
$filename = "somefile";  
$data = "stuff and thingsn";  
$tries = 10;  
if (lock($filename, $tries)) {  
       $h = fopen($filename, "a") or die();  
       fwrite($h, $data);  
       fclose($h);  
       /**  
         * 另外一个进程写文件,检查是否锁定  
       */  
       if (lock($filename, $tries)) {  
               $h2 = fopen($filename, "a") or die();  
               fwrite($h2,'check lock');  
               fclose($h2);  
        }else{  
            //die("Failed to lock $filename after ".($tries*100)." milliseconds!";  
        }  
        unlock($filename);  
} else {  
       //die("Failed to lock $filename after ".($tries*100)." milliseconds!";  
}  
?> 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools