好的,好的..所以现在我吓坏了。
index1.php
<?
function write_file($filepath,$filecontent) {
$openedfile = fopen($filepath,"w+"); //replace with $openedfile = fopen($filepath,"a"); just in case
flock($openedfile, LOCK_EX);
//add here fclose($openedfile); to work
//add here $openedfile = fopen($filepath,"w+"); to work
fwrite($openedfile,$filecontent);
flock($openedfile, LOCK_UN);
fclose($openedfile);
}
function read_file($filepath) {
$openedfile = fopen($filepath,"r+");
flock($openedfile, LOCK_SH);
sleep(10);
$filecontent = file_get_contents($filepath);
flock($openedfile, LOCK_UN);
fclose($openedfile);
return $filecontent;
}
write_file("Readme.txt","test 1");
$f1 = read_file("Readme.txt");
echo $f1;
?>
index2.php
<?
function write_file($filepath,$filecontent) {
$openedfile = fopen($filepath,"w+"); //replace with $openedfile = fopen($filepath,"a"); to work
flock($openedfile, LOCK_EX);
//add here fclose($openedfile); to work
//add here $openedfile = fopen($filepath,"w+"); to work
fwrite($openedfile,$filecontent);
flock($openedfile, LOCK_UN);
fclose($openedfile);
}
function read_file($filepath) {
$openedfile = fopen($filepath,"r+");
flock($openedfile, LOCK_SH);
$filecontent = file_get_contents($filepath);
flock($openedfile, LOCK_UN);
fclose($openedfile);
return $filecontent;
}
write_file("Readme.txt","test 2");
$f1 = read_file("Readme.txt");
echo $f1;
?>
我运行index1.php,然后在2秒后运行index2.php。 Index2.php按预期等待index1.php,但index1.php在10秒后没有显示任何内容,而index2.php显示“test 2”。 发生了什么事?
编辑:我想通了:D。我改变了$openedfile = fopen($filepath,"w+");
到
$openedfile = fopen($filepath,"a");
在第二个php中,它不再在index2.php执行时擦除readme.txt。
答案 0 :(得分:1)
当你打开要写入的文件时,你的readme.txt在很短的时间内实际上是空的,这不是必须做的吗?我认为PHP取出了整个文本,而不是将其替换为整个文本+添加。当index1.php想要读取文件时,index2.php可能刚刚清除了它?您可以在apache日志中检查这一点。
编辑:同样,在解锁文件后,index2.php立即控制它,用TEST 2覆盖TEST 1。