The fork() system call is used in Unix/Linux systems to create a new process by duplicating the calling process. Here's a complete and FAANG-level explanation of how it works:
🔹 What is fork()?
The fork() system call creates a child process that is a copy of the parent process. This is a fundamental system call for multitasking in Unix-based systems.
#include <unistd.h>
pid_t fork(void);
🔸 Return Values of fork()
✅ Example
📌 Output (example):
Parent process: child PID = 12345
Child process: my PID = 12345
🔍 Detailed Explanation
🔸 1. Cloning the Parent
fork() creates a separate child process with a copy of the parent’s memory, stack, heap, and file descriptors.
Both processes continue executing from the point where fork() was called.
🔸 2. Return Differentiation
This return value is crucial to distinguish execution flows:
Parent uses pid > 0 to know the child’s PID.
Child sees pid == 0, knows it's the child.
If fork() fails due to resource limits (e.g., max number of processes), it returns -1.
🔸 3. Process IDs
Each process gets its own unique PID.
The child gets a new PID, and the parent can track it using the returned PID.
🔧 Practical Use Cases
🚫 fork() Failure Cases
Returns -1 if:
Process limit reached (ulimit -u)
Not enough memory
OS policy blocks it
Debug:
🔄 Common Fork Pattern
⚠️ Interview Tip (FAANG)
Interviewers often check if you:
Know the return semantics of fork()
Can distinguish between parent and child
Handle errors properly
Understand zombie processes when wait() is missing
Avoid race conditions when using fork() in multithreaded programs
Would you like a fork vs exec vs clone vs vfork comparison table too?