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

在php中编辑公共临时文件以防止冲突,php,file-access,Php,File Access,我想有一个临时文件,可以随时更新。 我想做的是: <!-- language: lang-php --> // get the contents $s = file_get_contents( ... ); // does it need updating? if( needs_update() ) { $s = 'some new content'; file_put_contents( ... ); } //获取内容 $s=文件获取内容(…); //它需要更

我想有一个临时文件,可以随时更新。 我想做的是:

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

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

//获取内容
$s=文件获取内容(…);
//它需要更新吗?
如果(需要更新())
{
$s=‘一些新内容’;
文件内容(…);
}
我看到的问题是,无论什么条件导致“needs_update()”返回true,都可能导致多个进程同时(几乎)更新同一文件

在理想情况下,我会让一个进程更新该文件,并阻止所有其他进程读取该文件,直到我完成它

因此,只要调用“needs_update()”return 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( ... );
}

//如果有人正忙着写入文件,请在此处等待。
如果另一个进程正在处理文件(),请稍候;
//获取内容
$s=文件获取内容(…);
//它需要更新吗?
如果(需要更新())
{
//暂时阻止对文件的读/写访问
防止读取或写入文件并等待();
//重新生成新内容
$s=‘一些新内容’;
文件内容(…);
}
这样,只有一个进程可能更新文件,并且所有文件都将获得最新的值

有没有关于如何防止这种冲突的建议

谢谢


FFMG

您正在寻找flock功能。只要访问该文件的每个人都在使用它,flock就可以工作。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);

手册:

谢谢您的回答,很抱歉,这么长时间才回复您。