Simulate flock to implement file lock. It mainly provides an idea. $ Lock0 and $ lock1 are the object lock Identifiers. when a file is opened by a user, $ lock0 and $ lock1 are generated, when the file is not opened, there is no primary idea.
$ Lock0 and $ lock1 are the identifier of the file lock. when the file is opened by a user, $ lock0 and $ lock1 are generated. when the file is not opened, it does not exist.
In fact, the most important thing is to have an identifier to indicate the current state of the file. $ lock0 and $ lock1 play this role.
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 )){
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 );
/**
* Another process writes a file and checks whether the file 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! ";
}
Unlock ($ filename );
} Else {
// Die ("Failed to lock $ filename after". ($ tries * 100). "milliseconds! ";
}
?>
Bytes. $ Lock0 and $ lock1 are the identifier of the file lock. when the file is opened by a user, $ lock0 and $ lock1 are generated. when the file is not opened, it does not exist...