1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
/* !> Fork example [Ferd] 
 */

#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <stdio.h>

#include <assert.h>

int main(int argc, char **argv) {
  pid_t child; // Variable to store the child's process identifier

  printf("Creating 5 child processes\n");

  for (int i = 0; i < 5; ++i) {
    child = fork();
    if (child == 0) { // in the newly created child process
      printf("In child process %d\n", i);
      return i; // at this point, this child will exit with its number as exit code
    }
    else {
      printf("In the parent process. Just created child with PID %d\n", child);
      // parent continues working through the for loop
    }
  }

  // Now wait for 5 child processes to finish
  for (int i = 0; i < 5; ++i) {
    printf("Waiting for child to finish\n");
      int status;
      pid_t finished_child = wait(&status); // wait for a child to finish 
      printf("Child with PID %d finished with status %d\n", 
          finished_child, 
          WEXITSTATUS(status));
  }
  return 0;
}