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, 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 the 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); return 1;
return , 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); fopen($filename, "a ") or die();
lock $filename after ".($tries*100) . "Milliseconds!";;
}
unlock ($ filename);
} else {
//die ("Failed to Lock $ FILENAME AFTER". ($ Tries*100). ? & GT ;
The above has introduced flock to simulate flock to implement file locking, including flock aspects. I hope it will be helpful to friends who are interested in PHP tutorials.