pthread_atfork and PTHREAD_FORK

Ove Kaaven ovehk at ping.uio.no
Wed Sep 26 16:12:25 CDT 2001


On Wed, 26 Sep 2001, Bill Medland wrote:

> Is it legal for pthread_atfork to be called with null parameters (in which
> case I will correct PTHREAD_FORK, otherwise I'll assert the pointers).

NAME
       pthread_atfork - register handlers to be called at fork(2)
       time

SYNOPSIS
       #include <pthread.h>

       int  pthread_atfork(void  (*prepare)(void),  void   (*par­
       ent)(void), void (*child)(void));

DESCRIPTION
       pthread_atfork  registers  handler  functions to be called
       just before and just after a new process is  created  with
       fork(2).  The prepare handler will be called from the par­
       ent process, just before the new process is  created.  The
       parent  handler  will  be  called from the parent process,
       just before fork(2) returns. The  child  handler  will  be
       called   from  the  child  process,  just  before  fork(2)
       returns.

=>     One or several of the three handlers prepare,  parent  and
=>     child  can be given as NULL, meaning that no handler needs
=>     to be called at the corresponding point.

       pthread_atfork can be called several times to install sev­
       eral  sets  of handlers. At fork(2) time, the prepare han­
       dlers  are  called  in  LIFO  order   (last   added   with
       pthread_atfork,  first called before fork), while the par­
       ent and child handlers are called  in  FIFO  order  (first
       added, first called).

       To  understand  the purpose of pthread_atfork, recall that
       fork(2)  duplicates  the  whole  memory  space,  including
       mutexes in their current locking state, but only the call­
       ing thread: other threads are not  running  in  the  child
       process. Thus, if a mutex is locked by a thread other than
       the thread calling fork, that  mutex  will  remain  locked
       forever in the child process, possibly blocking the execu­
       tion of the child process. To avoid this, install handlers
       with  pthread_atfork as follows: the prepare handler locks
       the global mutexes (in locking order), and the parent  and
       child  handlers  unlock  them (in reverse order). Alterna­
       tively, prepare and parent can be set to NULL and child to
       a  function  that  calls  pthread_mutex_init on the global
       mutexes.

RETURN VALUE
       pthread_atfork returns 0 on success and a  non-zero  error
       code on error.

ERRORS
       ENOMEM insufficient  memory available to register the han­
              dlers.

AUTHOR
       Xavier Leroy <Xavier.Leroy at inria.fr>

SEE ALSO
       fork(2), pthread_mutex_lock(3), pthread_mutex_unlock(3).

                           LinuxThreads         PTHREAD_ATFORK(3)






More information about the wine-devel mailing list