flock simulates flock to implement file locking

WBOY
Release: 2016-07-29 08:36:19
Original
1164 people have browsed it

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.


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!