locking files on Linux

Oscar Benjamin oscar.j.benjamin at gmail.com
Thu Oct 18 11:31:42 EDT 2012


On 18 October 2012 16:08, andrea crotti <andrea.crotti.0 at gmail.com> wrote:
> 2012/10/18 Oscar Benjamin <oscar.j.benjamin at gmail.com>:
>>
>> Why not come up with a test that actually shows you if it works? Here
>> are two suggestions:
>>
>> 1) Use time.sleep() so that you know how long the lock is held for.
>> 2) Write different data into the file from each process and see what
>> you end up with.
>>
>
>
> Ok thanks I will try, but I thought that what I did was the worst
> possible case, because I'm opening and writing on the same file from
> two different processes, locking the file with LOCK_EX.
>
> It should not open it at all as far as I understood...

I don't think you have understood. Read the link that Grant posted:
http://en.wikipedia.org/wiki/File_locking#In_Unix-like_systems

And my other comment:

>> def write_to_file():
>>     with open(FILENAME, 'w') as to_lock:
>
> I don't think it will work if you truncate the file like this. This
> will empty the file *before* checking for the lock. Try opening the
> file for reading and writing (without truncating).

The lock is cooperative. It does not prevent the file from being
opened or overwritten. It only prevents any other process from
obtaining the lock. Here you open the file with mode 'w' which
truncates the file instantly (without checking for the lock).


Oscar



More information about the Python-list mailing list