2

OK、OK ..だから今、私はびっくりしています。

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");

2番目のphpで、index2.phpの実行時にreadme.txtをワイプしなくなりました。

4

1 に答える 1

1

これは、ファイルを開いて書き込むときに、readme.txtが実際には非常に短時間空であるという事実と関係がありませんか?PHPはテキスト全体を取り出して、それをテキスト全体と追加で置き換えたと思いました。index1.phpがファイルを読みたいとき、index2.phpはおそらくそれをクリアしましたか?ちなみに、これはapacheログで確認できます。

編集:また、ファイルのロックを解除した直後に、index2.phpがファイルを制御し、TEST1をTEST2で上書きします。

于 2012-08-04T09:39:01.387 に答える