Home  >  Article  >  Backend Development  >  Simulate flock to implement file locking_PHP tutorial

Simulate flock to implement file locking_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:57:521205browse

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.

Copy code The code is as follows:


// 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!";
}
?>

www.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...
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