The
pthread_atfork() function registers the provided handler functions to be called when the
fork(2) function is called. Each of the three handlers is called at a different place in the
fork(2) sequence. The
prepare handler is called in the parent process before the fork happens, the
parent handler is called in the parent process after the fork has happened, and the
child handler is called in the child process after the fork has happened. The
parent and
child handlers are called in the order in which they were registered, while the
prepare handlers are called in reverse of the order in which they were registered.
Any of the handlers given may be
NULL.
The intended use of
pthread_atfork() is to provide a consistent state to a child process from a multithreaded parent process where locks may be acquired and released asynchronously with respect to the
fork(2) call. Each subsystem with locks that are used in a child process should register handlers with
pthread_atfork() that acquires those locks in the
prepare handler and releases them in the
parent handler.