好的,好的..所以现在我吓坏了。
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。我变了
$openedfile = fopen($filepath,"w+");
至
$openedfile = fopen($filepath,"a");
在第二个 php 中,它不再在 index2.php 执行时擦除 readme.txt。