Re: How to make sure that the target file to read is not under writing by others?
| From: | Clancy | Date: | Thu, 20 Aug 2009 01:56:00 +0000 |
| Subject: | Re: How to make sure that the target file to read is not under writing by others? | ||
| References: | 1 2 3 4 5 6 7 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-296985@lists.php.net to get a copy of this message | ||
On Wed, 19 Aug 2009 08:13:56 -0400, kyle.smith@inforonics.com (Kyle Smith) wrote:
>Nitebirdz wrote:
>> On Wed, Aug 19, 2009 at 11:59:39AM +0100, Ashley Sheridan wrote:
>>
>>>
>>> No, what you're saying is 'use a log file in order to know when to look
>>> at another log file'. What would happen if you tried to access the
>>> control log file whilst it was in the process of being written to?
>>> Admittedly, you reduce your chances of failure because there is less
>>> data being written to the control log than the actual log, but the
>>> chance of reading incomplete data is still there!
>>>
>>>
>>
>> WARNING: total newbie here.
>>
>> If I understood Arno correctly, he was recommending to implement
>> something like the old "/var/run/*pid" files in UNIX. That way, you can
>> control whether or not the previous run is already done with the file
>> before you move on.
>That is definitely the correct approach. Have the script which copies
>the log file touch a file called 'log_file.write' or some such. When
>it's done, remove the file. Your PHP script should exit if that file
>exists. Of course, given the 30 minute cron cycle, it would then have
>to wait until the next cycle. Maybe run it more often.
I gather from this discussion that PHP allows two users to open a file for R/W? I had
assumed it wouldn't.
Anyway, how about:
$user = 'Fred'; $try_again = true;
If (!file_exists('Busy.txt'))
{
File_put_contents ('Busy.txt', $user);
If ($user == File_get_contents ('Busy.txt')
{
// Do what you have to
Unlink ('Busy.txt');
$try_again = false;
}
}
if ($try_again)
{
// Come back in 5 minutes
}
This has a theoretical weakness, in that Joe could check for Busy.txt in the interval
between your checking and writing it, and then write his copy after you had read your
copy. A moments delay between writing and re-reading would fix this.