Fork() Process

 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()

Returned Value

Meaning

> 0

Returned to the parent: PID of child.

0

Returned to the child process.

-1

Error: fork() failed (e.g., no memory).


✅ Example

#include <stdio.h>
#include <unistd.h>

int main() {
    pid_t pid = fork();

    if (pid > 0) {
        printf("Parent process: child PID = %d\n", pid);
    } else if (pid == 0) {
        printf("Child process: my PID = %d\n", getpid());
    } else {
        perror("fork failed");
    }

    return 0;
}


📌 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

Use Case

Behavior

Creating daemons

Detach from terminal with fork + setsid + second fork.

Multi-processing servers

Spawn child workers to handle requests.

Shells/terminals

Spawn each command as a new process via fork() + exec().


🚫 fork() Failure Cases

  • Returns -1 if:

    • Process limit reached (ulimit -u)

    • Not enough memory

    • OS policy blocks it

Debug:

ulimit -a        # View limits
dmesg | tail     # Kernel logs if fork fails



🔄 Common Fork Pattern

pid_t pid = fork();
if (pid == 0) {
    // Child process
    execvp(...); // Replace child with a new program
} else if (pid > 0) {
    wait(NULL)// Parent waits for child
} else {
    // Error
}



⚠️ 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?


Distributed by Gooyaabi Templates | Designed by OddThemes