CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 2 of 6 · 3 min read

fork

In plain words: Every process except the very first is created by another process. The creator is the parent and the new one is its child. A child can have children too, so the processes form a tree. Process 1 (Level 0, page 4) is at the top. A family is a fair picture, with one difference: a child process starts as a near copy of its parent, which no family manages.

The call fork() makes the copy. The kernel creates a new process that has its own PID and a copy of the parent's memory, registers and open files. Both processes then continue from the line after fork, and the call returns twice:

  • In the parent, it returns the PID of the child (a positive number).
  • In the child, it returns 0.
  • On failure, it returns -1 and no child exists.

That return value is how a program tells the two apart:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
    int x = 100;
    printf("before fork: pid %d\n", (int)getpid());
    fflush(stdout);
    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return 1; }
    if (pid == 0) {
        x = 200;
        printf("child:  pid %d parent %d x=%d\n", (int)getpid(), (int)getppid(), x);
        return 7;
    }
    int status;
    waitpid(pid, &status, 0);
    printf("parent: pid %d child %d x=%d exit=%d\n",
           (int)getpid(), (int)pid, x, WEXITSTATUS(status));
    return 0;
}

Output on the test machine (the PIDs change on each run):

before fork: pid 275
child:  pid 276 parent 275 x=200
parent: pid 275 child 276 x=100 exit=7

Three facts show up. The child's parent is 275, the original process. The child changed x to 200, but the parent's x is still 100: after the fork, the two processes have separate copies of memory (page 1, section 5). And the parent learned the child's exit code, 7, through waitpid.

The order of the lines from parent and child is not fixed. Here the parent printed last only because it waited for the child.

fork

fork is the Unix system call that creates a new process, the child, as a duplicate of the calling process, the parent. The child gets its own PID and its own copy of the parent's address space and open file descriptors, and runs on from the instruction after the call. fork returns the child's PID in the parent, 0 in the child, and -1 if no child could be made.

Example: after pid_t p = fork();, code in if (p == 0) runs only in the child, and the rest runs in the parent.

Check yourself: 1. What does fork return in the child? 2. After a fork, the child sets x = 200. What is x in the parent? 3. Why can a call to fork return -1?