Skip to content

Stage 20

Fork

Fork is used to spawn a child process from a parent process and grant its own address space.

The child process shares the heap of the parent process. Hence the memory allocated in the heap will be a shared memory between both the processes. However, if either the parent or the child process loads another program into its virtual address space using the exec system call, then the shared heap is detached from that process and surviving process will have the heap intact. The file pointers handled by the parent process are also shared by the child process.

The child will start executing from the point the parent has called Fork system call (the child starts fresh)

The child process will have a different PID and a new address space. However the child and the parent will share the code and heap regions of the address space.

The User Stack is copied so that the child starts with the exact same local variables and function call history as the parent

The Kernel Stack is set to empty. When the child process eventually gets scheduled to run for the first time, it doesn’t need to resume the parent’s kernel functions. Instead, it starts fresh.

The Per-Process Resource Table is copied to the child process as well. The child inherits all open files and semaphores that the parent had. If the parent was halfway through reading a file, the child starts at that exact same offset.

Feature Action Reason
User Stack Copied Child needs the same execution state/variables.
Kernel Stack Reset to Empty Child starts its own kernel-level lifecycle.
PID Unique Value OS must distinguish between the two processes.
PPID Set to Parent's PID Maintains the "Family Tree" of processes.
Resource Table Copied Child inherits open files and connections.

The Fork System call returns to the parent process. The parent resumes execution from the next instruction following the INT instruction invoking fork.

After completion of fork, the child process will be ready for execution and in CREATED state. The child process will begin execution from the instruction following the fork statement.

The fork would return the PID of the child to the parent and 0 to the child process.

Since the parent and child processes can concurrently access/modify the heap pages, they need support from the OS to synchronise access to the shared heap memory using Semaphores and Signal handling.

Note - Fork() can happen before allocating heap pages to the parent. Once the heap pages are allocated to the parent, same has to be shared with the child process as well.

Pasted image 20260127143015.png

Exit System Call

Exit System call has to update and clear the OS data structures of the terminating process and detach the memory pages allocated to the process from its address space.

Pasted image 20260127222934.png