about summary refs log tree commit diff
path: root/linuxthreads/man/pthread_atfork.man
blob: 4d06a56f8b99e77c8a07dded9a1cb2fc38ef2c2d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
.TH PTHREAD_ATFORK 3 LinuxThreads

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

.SH SYNOPSIS
#include <pthread.h>

int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void));

.SH 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 parent 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 several sets
of handlers. At !fork!(2) time, the |prepare| handlers are called in
LIFO order (last added with !pthread_atfork!, first called before !fork!),
while the |parent| 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 calling 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 execution 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). Alternatively, |prepare| and |parent| can be set to
!NULL! and |child| to a function that calls !pthread_mutex_init! on
the global mutexes.

.SH "RETURN VALUE"

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

.SH ERRORS
.TP
!ENOMEM!
insufficient memory available to register the handlers.

.SH AUTHOR
Xavier Leroy <Xavier.Leroy@inria.fr>

.SH "SEE ALSO"
!fork!(2),
!pthread_mutex_lock!(3),
!pthread_mutex_unlock!(3).