Interview Q&A / Operating Systems

BeginnerQuick answer1 min readUpdated 3 Oct 2026

What does fork() return, and how does a program use that value?

SHORT ANSWER

fork() creates a copy of the calling process. It returns 0 in the child, the child's PID in the parent, and -1 if creation failed. Programs branch on that value to run different code in each.

Explain it simply

Fork is like photocopying a form and handing the copy to a friend. Both of you now hold the same form, filled up to the same line, and continue from there. To tell the original from the copy, fork gives each a different answer to "what did fork return?".

  • In the child, fork returns 0.
  • In the parent, fork returns the child's process ID (a positive number).
  • On failure (no memory, process limit reached), it returns -1 and no child exists.

The child starts with a copy of the parent's memory, registers and open files, and resumes at the instruction right after the fork() call.

Example

c
#include <stdio.h>
#include <unistd.h>
int main() {
    pid_t pid = fork();
    if (pid < 0) {
        printf("fork failed\n");
    } else if (pid == 0) {
        printf("child\n");
    } else {
        printf("parent of %d\n", pid);
    }
    return 0;
}
// prints: "child" and "parent of <child pid>" in either order

The order of the two lines is not fixed; the scheduler decides which process runs first. If you need an order, make the parent call wait().

What to say in the interview

"fork returns 0 to the child, the child's PID to the parent, and -1 on error. I check for the error case first, then use pid == 0 for child code and the else branch for parent code. The output order between them is not guaranteed unless the parent waits."

Common mistakes

  • Assuming the parent always prints first.
  • Forgetting the -1 case.

#fork#process#unix

Related questions

Practise more Operating Systems questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Operating Systems quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.