fork(1) download
  1. /**
  2.  * File : 01fork.cpp
  3.  * Date of creation : December 29 2012
  4.  * Author : David Albertson
  5.  * Twitter : @DavidAlbertson
  6.  * Website : www.dalbertson.com
  7.  *
  8.  * Description :
  9.  * Creation of a child process and understanding how the chilPID value changes depending on which
  10.  * process we're in.
  11.  *
  12.  * Output :
  13.  * -----------------------------------
  14.  * Parent Process ID : <PID-Parent> .
  15.  * Child Process ID : <PID-Child> .
  16.  * Child Parent Process ID : <PID-Parent> .
  17.  * Printed by both process : <PID-Parent> .
  18.  * Printed by both process : <PID-Child> .
  19.  * -----------------------------------
  20.  *
  21.  * References :
  22.  * - http://w...content-available-to-author-only...e.net
  23.  * - http://l...content-available-to-author-only...e.net/man/3/fork
  24.  * - http://l...content-available-to-author-only...e.net/man/3/errno
  25.  *
  26.  */
  27.  
  28. #include <unistd.h> // for : fork()
  29. #include <sys/types.h> // for : pid_t
  30. #include <stdio.h> // for : perror, printf
  31. #include <errno.h> // for : errno
  32.  
  33. int main(int argc, char *arg[])
  34. {
  35. pid_t childPID; // Used to store the processID of the child process after the fork() call
  36. childPID = fork(); // Creation of a new process (commonly called child process)
  37.  
  38. // At this point, when the fork() call returns, a new (identical) process will be created.
  39. // If we are in the newly created process (the childProcess), the childPID variable will be 0.
  40. // Otherwise, if we are in the parent process the childPID variable will hold the value of the child PID.
  41. if(childPID >= 0) // The fork() call was successful
  42. {
  43. if(childPID == 0) // Code executed in the child process
  44. {
  45. printf("Child Process ID : %i .\n", getpid());
  46. printf("Child Parent Process ID : %i .\n", getppid());
  47. }
  48. else // Code executed in the parent process
  49. {
  50. printf("Parent Process ID : %i .\n", getpid());
  51. }
  52. }
  53. else if(childPID <0) // The fork call failed
  54. {
  55. printf("Fork failed with error code : %i .\n", errno);
  56. return 1;
  57. }
  58.  
  59. sleep(1); // Simply to make the output clear, printing this text at the end.
  60. printf("Printed by both process : %i .\n", getpid()); // Code executed by both process
  61.  
  62. return 0;
  63. }
Success #stdin #stdout 0.01s 2680KB
stdin
Standard input is empty
stdout
Parent Process ID : 15256 .
Printed by both process : 15256 .
Child Process ID : 15260 .
Child Parent Process ID : 15256 .
Printed by both process : 15260 .