POSIX semaphores and fork() -- when any process exits, they all lose , access

Daniel Eischen deischen at freebsd.org
Fri Feb 25 15:48:14 GMT 2005


On Fri, 25 Feb 2005, Robert Watson wrote:

> On Thu, 24 Feb 2005, Daniel Eischen wrote:
>
> > > If I create a named POSIX semaphore in a process, then fork(), the
> > > semaphore appears to be visible to both the parent and child.  However, as
> > > soon as the child exits, the semaphore disappears from the parent.  This
> > > seems likely incorrect, although I don't have a copy of the spec in
> > > question so couldn't say for sure.
> >
> >   http://www.opengroup.org/onlinepubs/009695399/functions/sem_open.html
>
> Hmm.  I haven't yet found a reference to fork() semantics for semaphores
> in the semaphore-related pages.  However, a bit of googling turned up the
> following references:
>
> - HIP's Tru64 documentation includes the words:
>
>   "The semaphore descriptor is inherited across a fork. A parent process
>   can create a semaphore, open it, and fork. The child process does not
>   need to open the semaphore and can close the semaphore if the
>   application is finished with it."

I think this is the desired behaviour.

> So it sounds like the semaphore references for a process basically need to
> be replicated for the child.  One hesitates to guess how this will
> interact with things like Linux threading.  The glibc POSIX semaphores
> documentation doesn't mention sem_open()/sem_close(), so maybe they only
> do semaphores in the context of the user thread library, and not
> inter-process semaphores.

The other thing to remember is that it isn't valid for a threaded
process to fork() and have the child process become threaded
again.  After a fork(), the child process has one thread and
the state of its mutexes, CVs, semaphores, etc., are left in
whatever their state was from before the fork.  The application
should use pthread_atfork() handlers if it needs to reuse any
of these in the child process.  So I don't think there is
anything that needs to be done in the thread libraries.

-- 
DE



More information about the freebsd-threads mailing list