好吧,好吧..所以現在我嚇壞了。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