Mainly provides an idea.
$lock0 and $lock1 are file lock identifiers. When the file is opened by a user, $lock0 and $lock1 will be generated. When the file is not opened, they will not exist.
In fact, the most important thing is to have an identifier to represent the current status of the file. $lock0 and $lock1 play such a role.
// Lock a file , timing out if it takes too long.
function lock ($lock, $tries) {
$lock0 = ".{$lock}0";
$lock1 = ".{$lock}1 ";
for ($i=0; $i<$tries; $i++) {
if (!is_file($lock0)) {
touch($lock0);
if (! is_file($lock1)) { >}
// 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);
/**
* Another process writes the file and checks whether it is locked
*/
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!"; " milliseconds!";
}
?>
http://www.bkjia.com/PHPjc/317723.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/317723.htmlTechArticle mainly provides an idea. $lock0 and $lock1 are file lock identifiers. When a file is opened by a user, $lock0 and $lock1 will be generated. When the file is not opened, it will not exist...