Simulate flock to implement file locking _ PHP Tutorial

Source: Internet
Author: User
Tags flock
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...

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.