1PTHREAD_ATFORK(3) Linux Programmer's Manual PTHREAD_ATFORK(3)
2
3
4
6 pthread_atfork - register fork handlers
7
9 #include <pthread.h>
10
11 int pthread_atfork(void (*prepare)(void), void (*parent)(void),
12 void (*child)(void));
13
14 Link with -pthread.
15
17 The pthread_atfork() function registers fork handlers that are to be
18 executed when fork(2) is called by this thread. The handlers are exe‐
19 cuted in the context of the thread that calls fork(2).
20
21 Three kinds of handler can be registered:
22
23 * prepare specifies a handler that is executed before fork(2) process‐
24 ing starts.
25
26 * parent specifies a handler that is executed in the parent process
27 after fork(2) processing completes.
28
29 * child specifies a handler that is executed in the child process
30 after fork(2) processing completes.
31
32 Any of the three arguments may be NULL if no handler is needed in the
33 corresponding phase of fork(2) processing.
34
36 On success, pthread_atfork() returns zero. On error, it returns an
37 error number. pthread_atfork() may be called multiple times by a
38 thread, to register multiple handlers for each phase. The handlers for
39 each phase are called in a specified order: the prepare handlers are
40 called in reverse order of registration; the parent and child handlers
41 are called in the order of registration.
42
44 ENOMEM Could not allocate memory to record the form handler entry.
45
47 POSIX.1-2001, POSIX.1-2008.
48
50 When fork(2) is called in a multithreaded process, only the calling
51 thread is duplicated in the child process. The original intention of
52 pthread_atfork() was to allow the calling thread to be returned to a
53 consistent state. For example, at the time of the call to fork(2),
54 other threads may have locked mutexes that are visible in the user-
55 space memory duplicated in the child. Such mutexes would never be
56 unlocked, since the threads that placed the locks are not duplicated in
57 the child. The intent of pthread_atfork() was to provide a mechanism
58 whereby the application (or a library) could ensure that mutexes and
59 other process and thread state would be restored to a consistent state.
60 In practice, this task is generally too difficult to be practicable.
61
62 After a fork(2) in a multithreaded process returns in the child, the
63 child should call only async-signal-safe functions (see signal-
64 safety(7)) until such time as it calls execve(2) to execute a new pro‐
65 gram.
66
67 POSIX.1 specifies that pthread_atfork() shall not fail with the error
68 EINTR.
69
71 fork(2), atexit(3), pthreads(7)
72
74 This page is part of release 4.15 of the Linux man-pages project. A
75 description of the project, information about reporting bugs, and the
76 latest version of this page, can be found at
77 https://www.kernel.org/doc/man-pages/.
78
79
80
81Linux 2017-09-15 PTHREAD_ATFORK(3)