Skip to the page

Operating systems · Write code

How many times does fork print?

The interviewer asks

How many times does this C program print hello, and why? Then tell me what fork returns.

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

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

Then

Follow-ups the interviewer asks next

  1. Draw the process tree.
  2. If the printf moves inside the loop, after the fork, how many lines print?
  3. What does fork return in the parent, in the child, and on failure?
  4. What is exec, and why do shells call fork and then exec?
  5. What happens if the parent never calls wait?
  6. Why can printf("hello") without the newline print more times than you expect?

The answer

What a strong answer covers

  • Each fork doubles the number of processes: 1 → 2 → 4 → 8. All 8 reach the printf, so it prints hello 8 times; in general, n forks in a row give 2^n processes, 2^n − 1 of them children.
  • With the printf inside the loop after the fork: 2 + 4 + 8 = 14 lines.
  • fork returns 0 in the child, the child's PID (a positive number) in the parent, and −1 if it fails (for example, too many processes).
  • The child gets a copy of the parent's memory; modern OSs share pages and copy only when one side writes (copy-on-write), so fork is cheap.
  • exec replaces the current program with a new one. A shell forks a child and the child execs the command, so the shell itself keeps running.
  • If the parent doesn't call wait, finished children stay as zombies until the parent exits.
  • Output order between processes isn't fixed. And text still in printf's buffer before a fork is copied into each child, so without a newline (or when output goes to a file or pipe) it can appear several times; call fflush(stdout) before fork.

The red pen

Common traps

Avoid:answering 3 or 4; saying the child starts from the top of main; not knowing the return values.

Practise this out loud

Say your answer out loud to an AI interviewer that follows up, and get a score for it.

Practise by voice

Practise questions like this out loud

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview