热搜:NVER node 开发 php

文件读写顺序问题

2024-09-05 14:25:01
文件读写顺序问题

<?phpfunction read($filename) {	$fp = fopen($filename, 'rb');	flock($fp, LOCK_SH);	$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 mt_rand(1, 999);}$file = './wr.txt'; //原文件是空的echo 'r1: ', read($file),       '|
';echo 'w1: ', write($file, 'a'), '|
';echo 'r2: ', read($file), '|
';echo 'w2: ', write($file, 'b'), '|
';echo 'r3: ', read($file), '|
';?>


实际执行之后的结果:
r1: |w1: 745|r2: |w2: 404|r3: |


根据结果发现,执行顺序和PHP语句的顺序不同,
实际上的顺序是“r1 -> r2 -> r3 -> w1 -> w2”。
我试过把读文件所加的锁LOCK_SH改成LOCK_EX,结果还是和上面的顺序一样。

怎样才能让读写顺序符合语句顺序“r1 -> w1 -> r2 -> w2 -> r3”来执行?


回复讨论(解决方案)

真正的原因是文件状态缓存造成 filesize($filename) 始终为 0

function read($filename) {    $fp = fopen($filename, 'rb');    flock($fp, LOCK_SH);    clearstatcache(); //清除文件状态缓存    $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'; //原文件是空的file_put_contents($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); //显示一下
r1: |
w1: a|
r2: a|
w2: b|
r3: ab|
ab


clearstatcache -- 清除文件状态缓存

本函数缓存特定文件名的信息,因此只在对同一个文件名进行多次操作并且需要该文件信息不被缓存时才需要调用 clearstatcache()。 

受影响的函数包括 stat(),lstat(),file_exists(),is_writable(),is_readable(),is_executable(),is_file(),is_dir(),is_link(),filectime(),fileatime(),filemtime(),fileinode(),filegroup(),fileowner(), filesize(),filetype() 和 fileperms()。

明白了,原来是缓存的缘故。