/* 
 * fork.c 
 *
 * Example on how to create a process using the fork() system
 * call. The program prints the list of process before and after
 * fork() is called.
 */

#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main() {
  pid_t pid;
  
  printf("Processes before forking:\n");
  system("ps -f");
  
  pid = fork();  /* the process is split here !! */
  
  /* 
   * Now we have two processes (child and parent) running on the
   * same executable code. The way we tell who we are is by
   * looking at the return value of fork() - 0 for the child
   * process and > 0 for the parent.
   */
  
  if (pid == 0) {   
    /* HERE WE ARE IN THE CHILD PROCESS */
    sleep(3);
  } else {
    /* HERE WE ARE IN THE PARENT PROCESS */
    printf("Child process id:  %d\n",pid);
    printf("Processes after forking:\n");
    system("ps -f");
  }

  /* Both processes exit here.
   * We could also have exited each separately 
   * within the if statement above */
  exit(0);
}
