2014-02-07 23 views
0

我想要一個不時更新的臨時文件。 我在想什麼做的是:在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

+0

http://stackoverflow.com/questions/5479580/is-there-a-risk-in-running-file-put-contents-on- the-same-file-from-different-p – user1844933

回答

0

您正在尋找羊羣功能。只要每個訪問該文件的人都在使用它,就會工作。從PHP手冊例如:

$fp = fopen("/tmp/lock.txt", "r+"); 

if (flock($fp, LOCK_EX)) { // acquire an exclusive lock 
    ftruncate($fp, 0);  // truncate file 
    fwrite($fp, "Write something here\n"); 
    fflush($fp);   // flush output before releasing the lock 
    flock($fp, LOCK_UN); // release the lock 
} else { 
    echo "Couldn't get the lock!"; 
} 

fclose($fp); 

手冊:http://php.net/manual/en/function.flock.php

+0

感謝您的回答,抱歉花了這麼長時間才找到您。 – FFMG

相關問題