Home > php教程 > php手册 > 模拟flock实现文件锁定

模拟flock实现文件锁定

WBOY
Release: 2016-06-13 12:34:14
Original
1118 people have browsed it

主要提供了一种思路。
  $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!";  
}  
?> 

source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template