Lesson 02intermediateProcesses

Process Creation with fork()

Process creation with fork(): the child gets a copy of memory (and of the output buffer), the classic fork-in-a-loop mistake and its fix, decoding how a child ended with waitpid(), a live zombie and an orphan, and timing with gettimeofday.

forkwaitwaitpidzombieorphan

How fork() Works

When fork() is called, the OS duplicates the current process. Both parent and child continue from the same point, but with different return values.

main() startsPID 1234fork()Parent (PID 1234)fork() returned 1235Child (PID 1235)fork() returned 0wait(NULL) — blocksdoes work, then exit(0)child reaped ✓
1

POSIX Includes Reference

A reference file listing the key POSIX headers used throughout the course: unistd.h, sys/types.h, sys/wait.h, and more.

00-some-includes.c
Reference — not run on its ownSnippets of common includes and calls — not a complete program.
2

First fork()

The simplest fork example — creating a child process and printing PIDs from both parent and child.

01-basic-forking.c
$ gcc -o basic_fork 01-basic-forking.c
$ ./basic_fork
Expected Outputclick Run to execute live
══════════════════════════════════════
  Your first fork() example
══════════════════════════════════════


[Parent] I am the parent process! My PID: 650, fork() returned child PID: 651
[Child]  I am the child process!  My PID: 651, my parent's PID: 650
3

The Child Gets a Copy

The child changes x, the parent's x stays 10 — and both print the same address &x. After fork() each process has its own copy of memory.

01a-fork-copy.c
/*
 * 01a-fork-copy.c — After fork() the child has a COPY of the parent's memory
 *
 * Key concepts: separate address spaces, same virtual address, wait()
 * Compile: gcc -o fork_copy 01a-fork-copy.c
 * Run:     ./fork_copy
 *
 * The child changes x. The parent's x does not change — even though both print
 * the same address &x. Each process has its own (virtual) memory.
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    int x = 10;
    printf("[Before fork] x = %d at address %p\n", x, (void *)&x);
    fflush(stdout);

    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }

    if (pid == 0) {                       // child
        x += 5;
        printf("[Child  %d] changed x to %d   (address %p)\n", getpid(), x, (void *)&x);
        exit(EXIT_SUCCESS);
    }

    wait(NULL);                           // parent: let the child finish first
    printf("[Parent %d] x is still %d    (address %p)\n", getpid(), x, (void *)&x);
    printf("Same address, different values: two separate copies of memory.\n");
    return EXIT_SUCCESS;
}
$ gcc -o fork_copy 01a-fork-copy.c
$ ./fork_copy
Expected Outputclick Run to execute live
[Before fork] x = 10 at address 0x7ffd177fc220
[Child  673] changed x to 15   (address 0x7ffd177fc220)
[Parent 672] x is still 10    (address 0x7ffd177fc220)
Same address, different values: two separate copies of memory.
4

Why Does It Print Twice?

fork() also copies the unwritten output buffer, so text printed without a newline comes out twice — and redirected to a file even whole lines double. Open out.txt in the Files panel. The fix: fflush(stdout) before fork().

01b-fork-buffer.c
/*
 * 01b-fork-buffer.c — Why does this line print twice? fork() copies the output buffer too
 *
 * Key concepts: stdio buffering, fflush(), line-buffered terminal vs fully-buffered file
 * Compile: gcc -o fork_buffer 01b-fork-buffer.c
 * Run:     ./fork_buffer                 (to the terminal)
 *          ./fork_buffer > out.txt       (to a file — then open out.txt in the Files panel)
 *
 * printf() does not write immediately: text waits in a buffer inside the process.
 * fork() copies the whole process — buffer included — so both copies print it later.
 * A terminal flushes at every '\n'; a file only when the buffer is full or at exit,
 * so redirected to a file even lines WITH '\n' come out twice.
 * (Here the very first line still appears once: this sandbox's C library, musl, decides
 *  "terminal or file?" at its first write. On a typical laptop with glibc, it doubles too.)
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    printf("1. A line ending with newline\n");
    printf("2. Another line ending with newline\n");
    printf("3. No newline yet... ");      // still sitting in the buffer

    pid_t pid = fork();                   // the buffer is copied into the child
    if (pid == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }

    if (pid == 0) {
        printf("[child]\n");
        exit(EXIT_SUCCESS);               // exit() flushes the child's copy of the buffer
    }
    wait(NULL);
    printf("[parent]\n");

    // The fix: call fflush(stdout) right before fork()
    return EXIT_SUCCESS;
}
$ gcc -o fork_buffer 01b-fork-buffer.c
$ ./fork_buffer; echo; ./fork_buffer > out.txt
Expected Outputclick Run to execute live
1. A line ending with newline
2. Another line ending with newline
3. No newline yet... [child]
3. No newline yet... [parent]
5

Fork-in-Loop Mistake vs The Fix: wait + exit

The classic bug: calling fork() inside a loop without exiting the child, causing exponential process creation. Compare side-by-side with the fix below.

Side-by-Side ComparisonChanged lines are highlighted
Bug02-basic-fork-mistake.c
/*
 * 02-basic-fork-mistake.c — The classic fork-in-a-loop bug
 *
 * Demonstrates: What goes WRONG when you fork() inside a loop without exiting
 * Key concepts: Exponential process creation, fork bomb pattern
 * Compile: gcc -o fork_mistake 02-basic-fork-mistake.c
 * Run:     ./fork_mistake
 *
 * BUG: The child process does NOT exit after printing — it continues the loop
 *      and calls fork() again! With 5 iterations, you get ~2^5 = 32 processes,
 *      not 5. See 03-basic-fork-thefix.c for the corrected version.
 */

#include <stdio.h>
#include <stdlib.h>    // for exit(), EXIT_FAILURE
#include <unistd.h>    // for fork(), getpid()

void check_valid_process(pid_t status);
int main()
{

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  The classic fork-in-a-loop bug\n");
    printf("══════════════════════════════════════\n\n");
    printf("  Watch: children don't exit, so they\n");
    printf("  loop again and fork MORE children!\n\n");

    for (int i = 0; i < 5; i++)
    {
        pid_t pid = fork(); // fork() creates a new process

        if (pid < 0)
        {
            // I RECOMMEND TO CREATE A FUNCTION FOR ALL FUTURE ERROR HANDLING
            // Fork failed
            perror("fork failed");
            return 1;
        }
        else if (pid == 0)
        {
            // BUG: Child prints but does NOT exit — it loops and forks again!
            printf("[Child  PID %d] iteration %d — BUG: I will keep looping and forking more children!\n", getpid(), i);
        }
        else
        {
            // Parent process
            printf("[Parent PID %d] iteration %d — created child PID %d\n", getpid(), i, pid);
        }
    }

  

    return 0;
}

// example check if the process is valid,else we exit the program
void check_valid_process(pid_t status)
{
    if (status < 0)
    {
        perror("Failed To open procceses");
        exit(EXIT_FAILURE);
    }
}
Fix03-basic-fork-thefix.c
/*
 * 03-basic-fork-thefix.c — Correct way to fork in a loop
 *
 * Demonstrates: Fixing the fork-in-a-loop bug from 02-basic-fork-mistake.c
 * Key concepts: Child must exit() after its work, parent must wait() for each child
 * Compile: gcc -o fork_fix 03-basic-fork-thefix.c
 * Run:     ./fork_fix
 *
 * Two fixes applied:
 *   1. Child calls exit(0) so it doesn't continue the loop
 *   2. Parent calls wait(NULL) to reap each child before forking the next
 */

#include <stdio.h>
#include <stdlib.h>    // for exit(), EXIT_FAILURE
#include <unistd.h>    // for fork(), getpid()
#include <sys/wait.h>  // for wait()

void check_valid_process(pid_t status);


int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Correct way to fork in a loop\n");
    printf("══════════════════════════════════════\n\n");
    printf("  Fixes: child calls exit(), parent\n");
    printf("  calls wait() before next fork.\n");

    const int RUNS = 5;
    pid_t status;
    for (int i = 0; i < RUNS; i++) {
        printf("\n--- Run %d ---\n", i + 1);
        
        pid_t pid = fork();  // fork() creates a new process

        if (pid < 0) {
            // Fork failed
            perror("fork failed");
            return 1;
        } else if (pid == 0) {
            // Child process
            printf("[Child  PID %d] Hello from child (run %d)! I will exit(0) now.\n", getpid(), i + 1);
            exit(0);  // FIX #1: Child exits here — won't continue the for-loop
        } else {
            // Parent process
            printf("[Parent PID %d] Created child PID %d. Waiting for it...\n", getpid(), pid);
            // FIX #2: Parent waits for child to finish before next iteration
            // wait(NULL) returns child PID on success, -1 on failure
            status = wait(NULL);
            if (status < 0) {
                perror("Failed to wait for child process");
                exit(EXIT_FAILURE);
            }
            else {
                printf("[Parent PID %d] wait() returned %d — child has been reaped.\n", getpid(), status);
            }
        }
    }

    return 0;
}

// Example function to check if the process is valid; exits if not
void check_valid_process(pid_t status) {
    if (status < 0) {
        perror("Failed to create process");
        exit(EXIT_FAILURE);
    }
}
Run both and compare the output
7

How Did My Child End?

Three children exit 0, exit 42 and crash; the parent decodes each status with WIFEXITED/WEXITSTATUS and WIFSIGNALED/WTERMSIG — the same information the site shows as "Exited 42" or "Killed by SIGSEGV".

03a-wait-status.c
/*
 * 03a-wait-status.c — How did my child end? Decoding the status from waitpid()
 *
 * Key concepts: waitpid(), WIFEXITED/WEXITSTATUS, WIFSIGNALED/WTERMSIG, exit codes
 * Compile: gcc -o wait_status 03a-wait-status.c
 * Run:     ./wait_status
 *
 * Three children end in three different ways. The parent learns how each one ended from
 * the status integer — the same information the site turns into "Exited 42" or
 * "Killed by SIGSEGV (11)", and that the shell keeps in $?.
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>    // strsignal
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    pid_t kids[3];

    for (int i = 0; i < 3; i++) {
        kids[i] = fork();
        if (kids[i] == -1) {
            perror("fork");
            return EXIT_FAILURE;
        }
        if (kids[i] == 0) {               // child i
            if (i == 0)
                exit(0);                  // ends normally
            if (i == 1)
                exit(42);                 // ends with an error code
            volatile int *p = NULL;       // child 2 crashes on purpose
            *p = 1;
        }
    }

    for (int i = 0; i < 3; i++) {
        int status;
        waitpid(kids[i], &status, 0);     // wait for THIS child
        printf("Child %d (PID %d): ", i, kids[i]);
        if (WIFEXITED(status))
            printf("exited with status %d\n", WEXITSTATUS(status));
        else if (WIFSIGNALED(status))
            printf("killed by signal %d (%s)\n", WTERMSIG(status), strsignal(WTERMSIG(status)));
    }
    return EXIT_SUCCESS;
}
$ gcc -o wait_status 03a-wait-status.c
$ ./wait_status
Expected Outputclick Run to execute live
Child 0 (PID 790): exited with status 0
Child 1 (PID 791): exited with status 42
Child 2 (PID 792): killed by signal 11 (Segmentation fault)
8

A Live Zombie

The child exits but the parent has not called wait(): ps shows it as Z <defunct>. After wait() collects the exit status, the zombie is gone from the process table.

03b-zombie-live.c
/*
 * 03b-zombie-live.c — See a zombie with your own eyes, then make it go away
 *
 * Key concepts: zombie (defunct) process, wait() reaps it, ps STAT column
 * Compile: gcc -o zombie 03b-zombie-live.c
 * Run:     ./zombie
 *
 * A child that has finished but was not yet wait()ed for stays in the process table
 * as a ZOMBIE (STAT Z, "<defunct>"): the kernel keeps its exit status for the parent.
 * wait() collects the status — and the zombie disappears.
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

static void show(pid_t pid)
{
    char cmd[64];
    snprintf(cmd, sizeof cmd, "ps -o pid,ppid,stat,comm -p %d", (int)pid);
    fflush(stdout);
    if (system(cmd) != 0)                 // ps exits 1 when the PID no longer exists
        printf("  (PID %d is gone from the process table)\n", (int)pid);
}

int main(void)
{
    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }
    if (pid == 0)
        exit(7);                          // child: finish immediately

    sleep(1);                             // parent: do NOT wait yet
    printf("Child %d has exited, but nobody called wait():\n", (int)pid);
    show(pid);

    int status;
    wait(&status);
    printf("\nAfter wait() (child's exit status: %d):\n", WEXITSTATUS(status));
    show(pid);
    return EXIT_SUCCESS;
}
$ gcc -o zombie 03b-zombie-live.c
$ ./zombie
Expected Outputclick Run to execute live
Child 818 has exited, but nobody called wait():
    PID    PPID STAT COMMAND
    818     816 Z+   zombie <defunct>

After wait() (child's exit status: 7):
    PID    PPID STAT COMMAND
  (PID 818 is gone from the process table)
9

Zombie Processes

What happens when a child exits before the parent calls wait — creating and observing zombie processes, with an explanation of orphan adoption by init.

01.5-forking-zombies.c
/*
 * 01.5-forking-zombies.c — Understanding zombie and orphan processes
 *
 * Demonstrates: What happens when parent doesn't wait() on children
 * Key concepts: Zombie processes, orphan adoption by init (PID 1), process table cleanup
 * Compile: gcc -o zombies 01.5-forking-zombies.c
 * Run:     ./zombies   (then check with: ps aux | grep Z)
 */

#include <stdio.h>

/*
In Unix-like operating systems (including Linux), the init process (with PID 1) plays a crucial role in process management. When a child process is left "orphaned" (because its parent process has terminated without waiting for it), the init process automatically adopts it. Here’s how this relates to zombies and waiting on child processes:

Understanding Zombies and Orphan Processes
Zombie Process:

A zombie process is a child process that has completed execution but remains in the process table because its parent hasn’t called wait() to read its exit status.
This process remains as a "zombie" until the parent either reaps it by calling wait() or the parent itself terminates, allowing the operating system to handle it.
Orphaned Process and init Adoption:

When a parent process terminates without waiting on its child processes, those children become "orphans."
The operating system automatically assigns these orphan processes to the init process (PID 1).
The init process is designed to continuously wait on all its children, so when it adopts an orphan process, it will eventually reap it, cleaning up any zombie state and freeing resources.
Automatic Cleanup by init:

This behavior allows zombie processes to be cleared even if the original parent process doesn’t explicitly call wait().
In effect, simply terminating the parent process will result in any zombie child processes being adopted and cleaned up by init.


Example: Creating and Observing Orphan and Zombie Processes
You can create zombie processes and let them be automatically cleaned up by init by ending the parent process without waiting on its children. Here’s an example:
*/


/// AT THIS POINT USE THE FOLLOWING:
// Use ps aux | grep Z
// to see the zombie process
Reference — not run on its ownExplains zombies and orphans in comments — there is no main() to run.
10

An Orphan Gets Adopted

The parent exits first; the still-running child reports its new parent, PID 1. Its last line appears after the prompt — the shell only waited for the parent.

03c-orphan.c
/*
 * 03c-orphan.c — When the parent dies first, the child is adopted
 *
 * Key concepts: orphan process, getppid() changes, adoption by PID 1 (init)
 * Compile: gcc -o orphan 03c-orphan.c
 * Run:     ./orphan     (the child's last line appears AFTER the prompt — that is the point)
 *
 * The parent exits after one second. The child is still running: it becomes an ORPHAN
 * and the system's first process (PID 1, "init") becomes its new parent, so it can
 * still be reaped when it ends. The shell already printed the prompt — it only waited
 * for the parent.
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    pid_t pid = fork();
    if (pid == -1) {
        perror("fork");
        return EXIT_FAILURE;
    }

    if (pid == 0) {                                   // child
        printf("[Child  %d] my parent is %d\n", getpid(), getppid());
        fflush(stdout);
        sleep(2);                                     // outlive the parent
        printf("\n[Child  %d] my parent is now %d — adopted after my parent exited\n", getpid(), getppid());
        return EXIT_SUCCESS;
    }

    printf("[Parent %d] created child %d, exiting in 1 second without waiting\n", getpid(), pid);
    fflush(stdout);
    sleep(1);
    printf("[Parent %d] bye\n", getpid());
    return EXIT_SUCCESS;
}
$ gcc -o orphan 03c-orphan.c
$ ./orphan
Expected Outputclick Run to execute live
[Parent 814] created child 815, exiting in 1 second without waiting
[Child  815] my parent is 814
[Parent 814] bye
11

Timing with gettimeofday

Using gettimeofday to measure elapsed time across parent and child processes.

04-forks-gettimeday.c
/*
 * 04-forks-gettimeday.c — Measuring parallel execution time with fork
 *
 * Demonstrates: Using gettimeofday() to time forked processes
 * Key concepts: Both parent and child run simultaneously — total time is ~2s, not ~4s
 * Compile: gcc -o fork_time 04-forks-gettimeday.c
 * Run:     ./fork_time
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>  // for gettimeofday(), struct timeval
#include <sys/wait.h>  // for wait()
#include <unistd.h>    // for fork(), sleep()

void perform_task() {
    // Simulate a task by sleeping for 2 seconds
    sleep(2);
}

int main() {

    printf("\n");
    printf("══════════════════════════════════════\n");
    printf("  Measuring parallel execution time with fork\n");
    printf("══════════════════════════════════════\n\n");
    struct timeval start, end;
    pid_t pid;
    double elapsed_time;
    printf("  Each process sleeps 2 seconds.\n");
    printf("  Sequential: ~4s. Parallel: ~2s.\n\n");

    gettimeofday(&start, NULL); // Get the start time

    pid = fork(); // Create a new process

    if (pid == -1) {
        // If fork() returns -1, an error occurred
        perror("Failed to fork");
        return 1;
    } else if (pid == 0) {
        // Child process
        perform_task();
        printf("[Child  PID %d] Task completed (slept 2 seconds)\n", getpid());
    } else {
        // Parent process
        perform_task();
        printf("[Parent PID %d] Task completed (slept 2 seconds). Waiting for child...\n", getpid());

        // Wait for the child to finish
        wait(NULL);
    }

    gettimeofday(&end, NULL); // Get the end time

    // Calculate the elapsed time in microseconds, then convert to seconds
    elapsed_time = (end.tv_sec - start.tv_sec) * 1000000.0; // sec to us
    elapsed_time += (end.tv_usec - start.tv_usec); // us
    elapsed_time /= 1000000.0; // convert back to seconds

    printf("[PID %d] Total elapsed time: %.2f seconds (both tasks ran in parallel!)\n", getpid(), elapsed_time);

    return 0;
}
$ gcc -o fork_time 04-forks-gettimeday.c
$ ./fork_time
Expected Outputclick Run to execute live
══════════════════════════════════════
  Measuring parallel execution time with fork
══════════════════════════════════════

  Each process sleeps 2 seconds.
  Sequential: ~4s. Parallel: ~2s.

[Parent PID 821] Task completed (slept 2 seconds). Waiting for child...
[Child  PID 822] Task completed (slept 2 seconds)
[PID 822] Total elapsed time: 2.01 seconds (both tasks ran in parallel!)
[PID 821] Total elapsed time: 2.01 seconds (both tasks ran in parallel!)

Challenges

ChallengeLesson 02

The fork() that fails

The loop asks for 200 children but your user may own only 64 processes. Detect the failing fork(), print why with perror("fork") and stop the loop. Click Edit, change the code, then Run — the site checks how it ended.

fork-limit.c
/*
 * Challenge (Lesson 02): the fork() that fails
 *
 * This loop asks for 200 children, but the sandbox lets your user own only 64
 * processes. Right now nobody notices when fork() fails — it returns -1, the
 * program treats -1 like a child's PID and carries on.
 *
 * Your task: detect the failure, print WHY with perror("fork"), and stop the loop.
 * Done when the output shows:  fork: Resource temporarily unavailable   (that is EAGAIN)
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

int main(void)
{
    int created = 0;
    for (int i = 0; i < 200; i++) {
        pid_t pid = fork();

        // TODO: if fork() returned -1, call perror("fork") and break out of the loop

        if (pid == 0) {       // child: wait a moment, then leave
            sleep(2);
            _exit(0);
        }
        created++;
    }
    while (wait(NULL) > 0)    // parent: collect every child (no zombies)
        ;
    printf("Asked for 200 children, really created %d\n", created);
    return 0;
}
$ gcc -Wall -o fork_limit fork-limit.c
$ ./fork_limit

Open Full Terminal

Get a Linux terminal with all 11 files from this lesson pre-loaded. Compile, run, and experiment freely.