PHP file lock Write instance sharing

Source: Internet
Author: User

PHP file Lock Write instance parsing.

Original address: http://www.jbxue.com/article/23118.html

PHP file Write method to deal with multi-threaded writing, the specific code:

functionFile_write ($file _name,$text,$mode= ' A ',$timeout=30){ $handle=fopen($file _name,$mode);  while($timeout>0){ if(Flock($handle, LOCK_EX)) {//exclusive locking of the sex$timeout--; Sleep(1); } } if($timeout> 0 ){ fwrite($handle,$text.‘ \ n '); Flock($handle,Lock_un); fclose($handle);//Release lock Actionreturn true; } return false; }

where the flock (int $handle, int $operation) function operation handle must be a file pointer that has already been opened.

Operation can be one of the following values:
To get a shared lock (read program), set operation to Lock_sh (the previous version of PHP 4.0.1 is set to 1).
To obtain an exclusive lock (written program), set operation to LOCK_EX (2 in previous versions of PHP 4.0.1).
To release the lock (either share or exclusive), set operation to Lock_un (3 in previous versions of PHP 4.0.1).
If you do not want flock () to block when locked, Operation plus LOCK_NB (set to 4 in previous versions of PHP 4.0.1).
In addition, fclose () is used to release the lock operation, which is called when the code finishes executing.

Articles you may be interested in:

    • PHP Flock File Lock Usage Example tutorial
    • PHP in flock file lock detailed

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.