/**
 * File: waitpid.c
 * ----------------
 * This program demonstrates how to use fork to create a child
 * process, and then use waitpid to wait for that process
 * to complete and then get informatio about its termination.
 */

#include <unistd.h>
#include <stdio.h>
#include <sys/wait.h>
#include "exit-utils.h"

static const int kForkFailed = 1;
static const int kWaitFailed = 2;
static const int childExitStatus = 110;

int main(int argc, char *argv[]) {
  printf("Before.\n");
  pid_t pidOrZero = fork();
  exitIf(pidOrZero == -1, kForkFailed, stderr, "Fork function failed.\n");
  printf("After.\n");
  if (pidOrZero == 0) {
    printf("I'm the child, and the parent will wait up for me.\n");
    sleep(5);
    printf("Child still here\n");
    return childExitStatus;
  } else {
    int status;
    //int result = waitpid(pidOrZero, &status, 0);
    //exitUnless(result == pidOrZero, kWaitFailed,
    //     stderr, "Parent's wait for child process with pid %d failed.\n", pidOrZero);
    if (WIFEXITED(status)) {
      printf("Child exited with status %d.\n", WEXITSTATUS(status));
    } else {
      printf("Child terminated abnormally.\n");
    }
    return 0;
  }
}
