我想要一個不時更新的臨時文件。 我在想什麼做的是:在php中編輯一個常見的臨時文件以防止衝突
<!-- language: lang-php -->
// get the contents
$s = file_get_contents(...);
// does it need updating?
if(needs_update())
{
$s = 'some new content';
file_put_contents(...);
}
,我可以看到發生的問題是,什麼條件導致「needs_update()返回true可能導致多個進程更多更新的同一個文件,(幾乎),同一時間。
在理想情況下,我會讓一個進程更新文件,並阻止所有其他進程讀取文件,直到完成它爲止。
因此,只要'needs_update()'返回true被調用,我會阻止其他進程讀取文件。
<!-- language: lang-php -->
// wait here if anybody is busy writing to the file.
wait_if_another_process_is_busy_with_the_file();
// get the contents
$s = file_get_contents(...);
// does it need updating?
if(needs_update())
{
// prevent read/write access to the file for a moment
prevent_read_write_to_file_and_wait();
// rebuild the new content
$s = 'some new content';
file_put_contents(...);
}
這樣,只有一個進程可能更新文件,文件都將獲得最新值。
關於如何防止這種衝突的任何建議?
感謝
FFMG
http://stackoverflow.com/questions/5479580/is-there-a-risk-in-running-file-put-contents-on- the-same-file-from-different-p – user1844933