Skip to content
We areTOP 1%

What does fork() do, and what does it return?

MediumConceptProcesses & Threads
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

Answer

fork() is the Unix/Linux system call that creates a new process, the child, as a copy of the calling process, the parent. Both continue from the instruction after fork(), and the return value tells them apart: 0 in the child, the child's PID in the parent, and -1 (negative) in the parent if no child could be created.

  • Copy-on-write (COW): parent and child initially share the same physical pages, marked read-only, and a page is copied only when one of them writes to it. This makes fork() fast.
  • Each then has its own copy of every variable, so a change in one is not seen by the other.
  • A shell runs a command by calling fork(); the child calls exec() to load the program while the parent calls wait().
  • Calling fork() n times in a row, unconditionally, gives 2^n processes in total.

Example:

int x = 10;
pid_t pid = fork();
if (pid == 0) { x++; printf("child: x = %d\n", x); }
else          { printf("parent: x = %d\n", x); }

Output (order may vary): parent: x = 10 and child: x = 11. Similarly, fork(); fork(); printf("hi\n"); prints hi four times.

More in Processes & Threads

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account