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.

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (FreeBSD)

iEYEARECAAYFAkkVmyEACgkQC3+MBN1Mb4h12ACfX/o6eL51AYGJRU8quBDpzQei
tJsAnj83rJWWyxXf5R3SyyeW1AY3AqzE
=Hnkw
-----END PGP SIGNATURE-----