A problem with fork() and subsequent flock()
Kostik Belousov
kostikbel at gmail.com
Sat Nov 8 06:38:37 PST 2008
On Sat, Nov 08, 2008 at 05:23:37AM +0530, Manish Jain wrote:
>
> Hi,
>
> I am starting out as a C/C++ programmer on FreeBSD and I am stuck with a
> small but irritating problem. I was trying out the flock() call and
> wrote flocksample.cpp, which starts out with a fork() and subsequent
> calls to flock() from both processes (parent as well as child; the child
> does an initial sleep(1) before anything else). It compiles okay and the
> parent's flock() call succeeds. But the child's flock() call too
> succeeds on the same file descriptor even before the first flock()
> unlocks. Can anyone please point out where the problem is ? I am not
> even sure whether the problem is FreeBSD specific.
This is right behaviour for flock. Note that manpage specifies that
lock is attached to file. When you open a filedescriptor, you get
the structure like that
fd -> file -> vnode
,-> means references.
Fork makes a copy of all fds opened in the process, and structure
becomes
fd [1] -> file -> vnode
fd [2] /
where fd[1] lives in parent, and fd[2] in child. Lock is still attached
to file, so both parent and child share the lock.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 195 bytes
Desc: not available
Url : http://lists.freebsd.org/pipermail/freebsd-fs/attachments/20081108/1b9197dc/attachment.pgp
More information about the freebsd-fs
mailing list