Exclusively lock a file to prevent other processes from reading it?

Christian Heimes lists at cheimes.de
Tue May 4 18:38:29 EDT 2010


python at bdurham.com wrote:
> Is there a way to exclusively lock a file to prevent other
> processes from reading it while we have it open?
>
> I need to cache some overflow data to disk in a temp file and I
> want to make sure no other processes can read the contents of
> this file while I'm using it.
>
> I tried the following using an 'append binary' mode, but I can
> use NotePad to read the file while I'm using it:
>
> fd = open( r'a-temp-file.dat', 'ab' )
>
> My environment is Python 2.6.4 (32-bit) under Windows, but I'm
> looking for a cross-platform solution if that's possible.

I know of now mandatory file lock solution that works cross platform. On 
Unix file locks (flock(2)) are advisory locks. All applications must 
check the file lock and act accordantly. Your best choice is other a 
temporary file or a temporary directory owned by your application. 
Python's tempfile module contains several solutions to securely work 
with temporary files and directories. Please don't try to come up with 
your own solution. Your app can easily become vulnerable by symlink attacks.

Christian




More information about the Python-list mailing list