好吧,好吧..所以现在我吓坏了。PHP文件同时访问
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显示“测试2”。 发生了什么事?
编辑:我想通了:d。我的第二个PHP改变
$openedfile = fopen($filepath,"w+");
到
$openedfile = fopen($filepath,"a");
而且不抹在index2.php执行readme.txt文件了。
看起来你释放锁之前写入文件。另见['fflush'](http://de.php.net/fflush)。 – hakre 2012-08-04 09:46:13