This is a discussion on Re: A problem with fork() and subsequent flock() - FreeBSD ; 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 ...
On Sat, Nov 08, 2008 at 05:23:37AM +0530, Manish Jain wrote:
> 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
fd  -> file -> vnode
fd  /
where fd lives in parent, and fd 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)
-----END PGP SIGNATURE-----