all Python 3Linux · macOSosfunction
os.fork
os — process creation
Fork a child process; returns 0 in the child and the child PID in the parent. Availability: Unix.
Syntax
os.fork(...)
It copies the whole process, but only the thread that called fork survives in the child: locks held by other threads stay held forever. That is why since 3.12 fork in a multithreaded program emits a DeprecationWarning, and on macOS fork without exec is unreliable altogether. For parallel work multiprocessing or subprocess is safer; the child exits via os._exit.
Examples
import os
data = [1, 2, 3]
pid = os.fork() # → ? только Unix (на Windows — AttributeError): в потомке 0, в родителе PID потомка, например 12345
data.append(pid) # → ? память скопирована: у потомка список станет [1, 2, 3, 0], у родителя [1, 2, 3, 12345]
if pid == 0: os._exit(0) # → ? потомок завершается немедленно, минуя atexit-обработчики и сброс буферов
print(os.waitpid(pid, 0)) # → ? только в родителе: (12345, 0) — второй элемент это сырой статус, а не код выхода (см. os.waitstatus_to_exitcode)
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy