2

好的,好的..所以现在我吓坏了。

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。

4

1 回答 1

1

这与您打开文件写入文件时您的 readme.txt 在很短的时间内实际上是空的这一事实有关吗?我认为PHP取出了整个文本,然后用整个文本+添加替换它。当 index1.php 要读取文件时, index2.php 可能刚刚清除了它?顺便说一下,您可以在 apache 日志中检查这一点。

编辑:此外,在解锁文件后,index2.php 立即控制它,用 TEST 2 覆盖 TEST 1。

于 2012-08-04T09:39:01.387 回答