RE: Is flock() necessary on a simple file append?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Kevin Grigorenko wrote:
> "Paul Fierro" <pablo@xxxxxxxxxxx> wrote in message
> news:BDA2E4B7.78402%pablo@xxxxxxxxxxxxxx
>> According to this post, you do not need to use flock() if you open a
>> file in append mode:
>>
>> http://marc.theaimsgroup.com/?l=php-general&m=105165806915109&w=2
>
> That's exactly what I was looking for; however, I wonder whether that
> only applies to the one byte the poster speaks of, or as long as
> everyone is only appending.

This is my understanding, someone correct me if I'm wrong...

AFAIK, normally you need to lock even on appending.  Depending on how the OS buffers
disk writes (and how much data you are writing), it's possible that a portion of
process A's data will be written, then a portion of process B's, etc (interleaving).
You could end up with garbage data in your file if you don't ensure that the each
writer has exclusive write access.  In Rasmus's example you are only writing single
bytes, and the order that they are eventually written doesn't matter.  Each single
byte will be written as one operation (as opposed to being buffered into separate
writes if your data is larger) and it doesn't matter if process B gets to the file
before process A.  But if the amount of data you are writing is larger than what the
OS buffers then you could get interleaving data being written from concurrent
processes.

See:
http://groups.google.com/groups?selm=8c10kl%24frg%241%40rguxd.viasystems.com

That thread is from comp.lang.perl.misc, but what is discussed should apply to PHP
as well.

>From your original post it looks like you aren't writing a lot of data per request,
so you probably won't have any problems with interleaving.  However, calling flock()
is fairly simple so I would if your data is important.

HTH

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux