pthread_atfork(3P) pthread_atfork(3P)
pthread_atfork - register fork() handlers
#include <pthread.h>
int pthread_atfork(void (*prepare)(void), void (*parent)(void),
void (*child)(void));
The pthread_atfork() function registers three functions which are invoked
when any thread calls fork(). If prepare is not NULL it must be a
function that will be called prior to the actual fork() in the parent
context. Similarly, parent and child, if not NULL, will be called after
fork() in the contexts of the parent and child respectively. Multiple
calls to pthread_atfork() are possible; prepare handlers are run in the
opposite order to which they were registered and parent and child
handlers in the order they were registered.
When fork() is called from a threaded application a new process is
created with a single thread (the caller); other threads which may be
running in the parent do not exist in the child. A side effect of this
behavior is that locks which protect data in the process may be held in
the child by threads which no longer exist. If the single surviving
thread were to encounter these locks it would wait indefinitely.
Using fork() handlers an application may protect its own data by
synchronizing its state with respect to fork(). Typically this means
adding a prepare handler to acquire a lock and parent and child handlers
to unlock it again, ensuring that the child may use the lock (and
associated data) as usual.
Although an application may protect its own data in this way, libraries
it uses may not. Therefore the child process should restrict itself to
its own code and to system calls. This restriction is less onerous than
it appears since the most common reason for using fork() in a threaded
application is in order to start a new process with exec().
On success pthread_atfork() returns zero; otherwise an error number is
returned:
[ENOMEM] Memory cannot be allocated to record the handlers.
fork(2), exec(2).
PPPPaaaaggggeeee 1111 [ Back ]
|