Linux file locks ?

Padraig at Linux.ie Padraig at Linux.ie
Thu Mar 27 12:55:10 CET 2003


Robert wrote:
> Need a simple but strict and secure exclusive file (global) lock. "if not
> os.path.exist: open(..'w') ... "  is weak - you get no guarantee.
> 
> I ended in:
> 
> -----
> # access the unique lock ...
> lock=open(fn_lock,'w')
> import fcntl
> try: fcntl.lockf(lock, fcntl.LOCK_EX|fcntl.LOCK_NB)    #exclusive lock
> except IOError:
>     fcntl.lockf(lock, fcntl.LOCK_UN)    #if I don't do this the second trial
> overruns an other process !?
>     raise
> try:
>     ...protected mainloop...
> finally:
>     lock.close();
> ----
> 
> but whats funny, even if a file is opened and locked this way, it maybe
> deleted (rm
> x.lock) without a notice!? How would one lock a file against removing ?
> 
> Is there a simple method to get a nice stable lock?

Hmm what you seem to want is a mandatory lock.
To support that you need to mount your filesystem with the mand option
For e.g. mount -o remount,mand /
more info @ http://infradead.org/~willy/locking_manifesto.html

Are you sure you need this though? It's looks like you
have cooperating processes? Who would delete the lock file?
Another option for atomic (cooperative) locking is to
just try create a directory.

Pádraig.





More information about the Python-list mailing list