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

Re: [afnog] lockf() and open() : Theoretical Questions



On Sat, 26 Jul 2003, Begumisa Gerald M. wrote:
> 1) Does anyone know of an implementation of mandatory file locking in
>    FreeBSD (similar to that provided in linux from the lockf()
>    interface)?  I've read the lockf(3), flock(2) and fcntl(2) man pages
>    all imply advisory-mode locks.

I don't know what linux lockf() does, but in FreeBSD and NetBSD, the
locks set by lockf() are advisory.  This conforms to XPG4.2.

Other cooperating processes can tell that you have set an advisory lock,
but non-cooperating processes are not prevented from reading/writing the
file.

> 2) [...] Now here came the problem, how could I delete the contents of the
>    original file without losing the locks for even the shortest possible
>    period of time and write back the data from the temporary file.

Don't try to write the data back.  Instead, use rename(3) to atomically
rename the temp file.

	open and lock the old file;
	create, open and lock a new temp file in the same file system;
	copy the data you want into the temp file;
	rename the temp file to make it replace the old file;

Just before the rename(), both old and new files are open and locked,
and any other process trying to open the file by name will get the old
version.  The rename() is atomic.  Just after the rename, both old and
new files are open and locked, and any other process trying to open the
file by name will get the new version.  As soon as you close the old
file, it disappears, because there are no directory entries referring to
it.

--apb (Alan Barrett)
__________________________________________________
This is the Africa Network Operators' Group(AfNOG) 
technical discussion list.
The AfNOG website is: <http://www.afnog.org>