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

int main(int argc, char **argv)
{
  pid_t pid1, pid2;

  pid1 = fork();

  if (pid1 < 0) {
    fprintf(stderr,"Error: can't fork a process\n");
    perror("fork()");
    exit(1);
  } else if (pid1) { // I am the parent

    pid2 = fork();

    if (pid2 < 0) {
      fprintf(stderr,"Error: can't fork a process\n");
      perror("fork()");
      exit(1);
    } else if (pid2) { // I am still the parent
      pid_t waited1, waited2;
      int status1, status2;

      // waiting for a child
      waited1 = wait(&status1);
      if (waited1 == -1) {
        perror("wait()");
      } else {
        fprintf(stdout,"I am the parent: child with pid %d exited with code %d\n",
                waited1, WEXITSTATUS(status1));
      }
      // waiting for another child
      waited2 = wait(&status2); 
      if (waited2 == -1) {
        perror("wait()");
      } else {
        fprintf(stdout,"I am the parent: child with pid %d exited with code %d\n",
                waited2, WEXITSTATUS(status2));
      }

      exit(0);
    } else {  // second child
      sleep(1); 
      exit(42);
    }
  } else {  // first child
    sleep(3);
    exit(66);
  }
}

