'; Echo ' W1: ', write ($file, ' a '), ' |
'; Echo ' R2: ', read ($file), ' |
'; Echo ' W2: ', write ($file, ' B '), ' |
'; Echo ' R3: ', read ($file), ' |
';? >
Results after the actual execution:
R1: |w1:745|r2: |w2:404|r3: |
According to the results, the order of execution and the order of the PHP statements are different.
In fact the order is "W2, W1, R3, R2, R1,".
I tried to change the lock lock_sh to LOCK_EX, and the result was the same as in the above order.
How can I make the read-write order conform to the sentence order "R1, W1, R2, W2, R3"?
Reply to discussion (solution)
The real reason is that the file state cache causes filesize ($filename) to always be 0
function Read ($filename) { $fp = fopen ($filename, ' RB '); Flock ($FP, lock_sh); Clearstatcache (); Clears the file state cache $data = @fread ($fp, @filesize ($filename)); Fclose ($FP); return $data;} function Write ($filename, $data) { $fp = fopen ($filename, ' ab '); Flock ($FP, lock_ex); Fwrite ($fp, $data); Fclose ($FP); return $data;//mt_rand (1, 999);} $file = './wr.txt '; The original file is empty file_put_contents ($file, '); Empty the source file Echo ' R1: ', read ($file), ' |
'; Echo ' W1: ', write ($file, ' a '), ' |
'; Echo ' R2: ', read ($file), ' |
'; Echo ' W2: ', write ($file, ' B '), ' |
'; Echo ' R3: ', read ($file), ' |
'; ReadFile ($file); Show me a bit
R1: |
w1:a|
r2:a|
w2:b|
r3:ab|
Ab
Clearstatcache--Clears the file status cache
This function caches information for a specific file name, so you need to call Clearstatcache () only if you have multiple operations on the same file name and require that the file information not be cached.
The affected functions include stat (), Lstat (), file_exists (), is_writable (), is_readable (), is_executable (), Is_file (), Is_dir (), Is_link (), Filectime (), Fileatime (), Filemtime (), Fileinode (), filegroup (), Fileowner (), filesize (), filetype () and fileperms ().
Understand, the original is the reason for the cache.