Henry Hoang

Appendix-04.Fork_in_Unix

Appendix-04.Fork_in_Unix

What is os.fork

import os

pid = os.fork()

if pid == 0:
    print("I am the child process!")
else:
    print(f"I am the parent process. My child has PID {pid}")

Use case: Pipes for Parent–Child Communication

Python’s os.pipe() creates two file descriptors:

  • r — read end

  • w — write end

After fork(), the parent and child each inherit both ends, so you must close the unused ends in each process.

import os

# Create a pipe: r for reading, w for writing
r, w = os.pipe()

pid = os.fork()

if pid == 0:
    # --- Child process ---
    os.close(r)  # child doesn't read

    message = b"Hello from child!"
    os.write(w, message)
    os.close(w)  # important: tell parent we are done writing
else:
    # --- Parent process ---
    os.close(w)  # parent doesn't write

    # Read data sent by child
    data = os.read(r, 1024)
    print("Parent received:", data.decode())

    os.close(r)

Use case: Pipes for Bidirectional communication

To communicate both ways, you use two pipes:

  • Pipe 1: parent → child

  • Pipe 2: child → parent

Here’s a minimal round-trip example:


import os
import time
# Create two pipes
pr, pw = os.pipe()  # parent writes, child reads
cr, cw = os.pipe()  # child writes, parent reads

pid = os.fork()

if pid == 0:
    # --- Child ---
    os.close(pw)
    os.close(cr)

    msg = os.read(pr, 1024) # Will block to wait compuate
    print("Child got:", msg.decode())

    reply = b"Message received!"
    os.write(cw, reply)

    os.close(pr)
    os.close(cw)
else:
    # --- Parent ---
    os.close(pr)
    os.close(cw)

    print("[Parent] Started, waiting 2 seconds before sending message...")
    time.sleep(2)


    os.write(pw, b"Hello child!")
    reply = os.read(cr, 1024)
    print("Parent got:", reply.decode())

    os.close(pw)
    os.close(cr)

Use case: call a function from child process


import os

def my_func(x, y):
    print(f"Child running my_func with {x=} and {y=}")

pid = os.fork()

if pid == 0:
    # This is the child process
    my_func(10, 20)
    os._exit(0)       # terminate child cleanly
else:
    # This is the parent process
    print(f"Parent: child PID is {pid}")

Child process will be copied global variables from parent

On this page