Winter Semester 2026–27 · VIT-AP · BACSE106 · Operating Systems · Dr. Krithika L.B

fork() explorer

Step through fork() programs and predict their output.

Module 2 Session 2.2 Lesson 2 of 2

fork() explorer

Predict, then step through — how many processes, and what do they print?

Puzzle 1 — one fork

p1.c
int main(void) {
    printf("A\n");
    fork();
    printf("B\n");
    return 0;
}

One process prints A.

fork() creates a child. Both parent and child continue at the next statement.

Both print B. Output: A B B (the two B's may appear in either order — the scheduler decides).

Puzzle 2 — forks in a loop

p2.c
int main(void) {
    for (int i = 0; i < 3; i++)
        fork();
    printf("hello\n");
    return 0;
}

1 process forks → 2 processes, both continue the loop with i = 1.

Each of the 2 forks → 4 processes.

Each of the 4 forks → 8 processes.

All 8 print hello. In general, n forks in sequence give 2n processes (2n − 1 new).

Puzzle 3 — using the return value

p3.c
int main(void) {
    int x = 10;
    pid_t pid = fork();
    if (pid == 0) { x = x + 5; printf("child x=%d\n", x); }
    else          { wait(NULL); x = x - 5; printf("parent x=%d\n", x); }
    return 0;
}

After fork() the child has its own copy of x = 10. Memory is not shared.

Child: pid == 0 → x = 15, prints child x=15.

Parent waits for the child, then x = 5 (its own copy!), prints parent x=5.

Changes in one process are invisible to the other. To share data, processes need IPC — Module 3.

Quick check

How many processes exist after fork(); fork();?

1 → 2 → 4.

In the child, fork() returns…

0 identifies the child; the parent gets the child's PID.

A child exits but the parent never calls wait(). The child is a…

Its exit status sits in the process table until collected.

The parent exits while the child is still running. The child becomes…

Linux re-parents orphans to init/systemd (or a subreaper).