Вопрос

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

Это было полезно?

Решение

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

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

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top