dongxi6897 2014-02-07 10:50 采纳率: 0%
浏览 18
已采纳

在php中编辑公共临时文件以防止冲突

I want to have a temp file that gets updated from time to time. What I was thinking of doing is:

<!-- language: lang-php -->
// get the contents
$s = file_get_contents( ... );

// does it need updating?
if( needs_update() )
{
    $s = 'some new content';
    file_put_contents( ... );
}

The issue that I could see happening is that whatever condition causes 'needs_update()' to return true could cause more than one process to update the same file at, (almost), the same time.

In an ideal situation, I would have one single process updating the file and prevent all other processes from reading the file until I am done with it.

So as soon as 'needs_update()' return true is called I would prevent others processes from reading the file.

<!-- 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( ... );
}

That way, only one process could possibly update the file and the files would all be getting the latest values.

Any suggestions on how I could prevent such a conflict?

Thanks

FFMG

  • 写回答

1条回答 默认 最新

  • dsdv76767671 2014-02-07 10:54
    关注

    You are looking for the flock function. flock will work as long as everyone that acess the file is using it. Example from php manual:

    $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
    ");
        fflush($fp);            // flush output before releasing the lock
        flock($fp, LOCK_UN);    // release the lock
    } else {
        echo "Couldn't get the lock!";
    }
    
    fclose($fp);
    

    Manual: http://php.net/manual/en/function.flock.php

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应