主要提供了一种思路。
$lock0和$lock1就是文件锁定的标识符,当文件被某一用户打开的时候,$lock0和$lock1就会产生,当该文件没打开则不存在。
其实最关键就是有个标识符来表示当前这个文件的状态, $lock0和$lock1就是起这样的作用。
<?php <br><br>// Lock a file, timing out if it takes too long. <BR>function lock ($lock, $tries) { <BR> $lock0 = ".{$lock}0"; <BR> $lock1 = ".{$lock}1"; <BR> for ($i=0; $i<$tries; $i++) { <BR> if (!is_file($lock0)) { <BR> touch($lock0); <BR> if (!is_file($lock1)) { <BR> touch($lock1); <BR> return 1; <b>/本文来源gao@!dai!ma.com搞$$代^@码5网@</b><strong>搞代gaodaima码</strong> <BR> } <BR> } <BR> usleep(100); <BR> } <BR> return 0; <BR>} <br><br>// Unlock a file. <BR>function unlock ($lock) { <BR> unlink(".{$lock}1"); <BR> unlink(".{$lock}0"); <BR>} <br><br>// Usage example. <BR>$filename = "somefile"; <BR>$data = "stuff and thingsn"; <BR>$tries = 10; <BR>if (lock($filename, $tries)) { <BR> $h = fopen($filename, "a") or die(); <BR> fwrite($h, $data); <BR> fclose($h); <BR> /** <BR> * 另外一个进程写文件,检查是否锁定 <BR> */ <BR> if (lock($filename, $tries)) { <BR> $h2 = fopen($filename, "a") or die(); <BR> fwrite($h2,'check lock'); <BR> fclose($h2); <BR> }else{ <BR> //die("Failed to lock $filename after ".($tries*100)." milliseconds!"; <BR> } <BR> unlock($filename); <BR>} else { <BR> //die("Failed to lock $filename after ".($tries*100)." milliseconds!"; <BR>} <BR>?> <BR>