3.1 Fork

The system call to create a new process is fork. fork is a very primitive system call, and its prototype is included in unistd.h. The fork call does not have any parameters, and its return value is very interesting:

The following simple program illustrates this:

#include <stdio.h> 
#include <unistd.h> 
 
int main(void
{ 
  int childPID; 
  getchar(); /* delay the parent from forking */ 
  childPID = fork(); 
  switch (childPID) 
  { 
    case 0: /* I am the child (new) process */ 
      printf(”I_am_the_child_process.\n”); 
      for (;;) sleep(1); /* just so that we can PS the child */ 
      break
    case -1: /* I am the parent, and something is wrong */ 
      printf(”I_am_the_parent.\n”); 
      perror(”Parent”); 
      break
    default
      printf(”I_am_the_parent,_the_child_is_%d.\n”, childPID); 
      for (;;) sleep(1); /* just so that we can PS the parent */ 
      break
  } 
  return 0; 
}

To test this program, prepare two terminals. Run the program in the first terminal. Run ps -A --forest in the second. You should find the process by its name. Press the ENTER key in the first terminal. This unblocks the getchar call so that the program will create a child process. Switch back to the second terminal, and run ps -A --forest again.

This time, you should find two processes of the same name. Furthermore, one will be listed as a child of the other. This confirms that the fork operation was successful.

Use killall progname (replace progname with the actual name of the program) to kill all instances of the program. Or, you can press control-C in the first terminal. This kills the parent process, which in return kills the child process.