Operation Systems fork() Method

The process calls the fork() system call, which the OS provides as a way to create a new process. The original process is known as the parent and the new process is known as the child.

The child process that is created is almost an exact copy of the original process. To the Operating System, there are now 2 copies of the process that can both return from the fork() system call.

The child process doesn’t start running at main(), it just comes into life as if it had called fork() itself.

Athough the two processes are essentially the same. They return different values to fork() so that we can differentiate them.

The following C++ code from “Operating Systems: Three Easy Pieces” illustrates this very well.

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

int main(int argc, char *argv[]) {
 printf("hello world (pid:%d)\n", (int) getpid());
 int rc = fork();
 if (rc < 0) { // fork failed; exit
  fprintf(stderr, "fork failed\n");
  exit(1);
 } else if (rc == 0) { // child (new process)
  printf("hello, I am child (pid:%d)\n", (int) getpid());
 } else { // parent goes down this path (main)
  printf("hello, I am parent of %d (pid:%d)\n",
   rc, (int) getpid());
 }
 return 0;
}

Returns the following output

prompt> ./p1
hello world (pid:29146)
hello, I am parent of 29147 (pid:29146)
hello, I am child (pid:29147)
prompt>