PHP file Lock Read and write note

Source: Internet
Author: User

It is said that the text mode is prone to file lock failure, such as messy problems.

In fact, it is not ineffective, but the wording is somewhat wrong.

After the lock_ex file is fopen in read mode, the empty content is read!!!

If you do not have the judgment to do it after the operation and then write a mistake ....

A lot of the problems are here.


Just to add

If a file is fopen in write mode and flock (... LOCK_EX).

There is another program at this time to fopen it, and also to Flock (LOCK_EX), this must be a mistake.

Because the size of the file may have been truncate to 0 by the second fopen.

Do a test-------------below---------------

Test program 1. :::: 1.php
<?php
$FD = fopen ("./test.txt", "w");
Flock ($FD, LOCK_EX);
Sleep (10);
Fwrite ($FD, "Hightman");
Flock ($FD, lock_un);
Fclose ($FD);
?>

Test program 2. :::: 2.php
<?php
$FD = fopen ("./test.txt", "R");
Echo fread ($FD, 512);
Fclose ($FD);
?>
Test Procedure 3::::: 3.php
<?php
if ($FD = @fopen ("./test.txt", "r+")) {
Flock ($FD, LOCK_EX);
Fseek ($FD, 0, seek_end);
Fwrite ($FD, "shit");
Flock ($FD, lock_un);
Fclose ($FD);
}
?>

Program test Method 1: Run 1.php and then go to run 2.php, 2.php output result is empty.
2: Run 1.php then go to run 3.php, 3.php will end after 1.php run
But the result file content is: "Shit" instead of "Hightmanshit"

So pay special attention to what happens when you write.
"W", "r+", "a", "A +" should pay attention to the file length of 0! The file may be empty, or it may be flock



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.