---
name: "pthread_atfork"
section: "3thr"
platform: "linux"
package: "glibc-doc"
version: "2.1.3-20"
release: "Debian 2.2 (Potato)"
platforms: ["linux"]
url: "https://new.carta.tech/pthread_atfork/3thr"
---

# pthread\_atfork(3thr)

register handlers to be called at fork(2) time

## NAME

pthread\_atfork - register handlers to be called at [fork(2)](/fork/2.md) time

## SYNOPSIS

**#include \<pthread.h\>**

**int pthread\_atfork(void (\****prepare***)(void), void (\****parent***)(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)](/fork/2.md). 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)](/fork/2.md) returns. The  *child* handler will be called from the child process, just before  [**fork**(2)](/fork/2.md) 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)](/fork/2.md) 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)](/fork/2.md) 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.

## RETURN VALUE

**pthread\_atfork** returns 0 on success and a non-zero error code on error.

## ERRORS

- **ENOMEM**

  insufficient memory available to register the handlers.

## AUTHOR

Xavier Leroy \<Xavier.Leroy@inria.fr\>

## SEE ALSO

[**fork**(2)](/fork/2.md), [**pthread\_mutex\_lock**(3)](/pthread_mutex_lock/3.md), [**pthread\_mutex\_unlock**(3)](/pthread_mutex_unlock/3.md).
