/**
 * File: separate.c
 * ----------------
 * Here's is a program that's written in a style more conistent with
 * how fork is normally used.
 */

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

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

int main(int argc, char *argv[]) {
    pid_t pidOrZero = fork();

    // Optional error checking
    if (pidOrZero == -1) {
        fprintf(stderr, "Error: fork failed\n");
        return kForkFailed;
    }

    if (pidOrZero == 0) {
        printf("I'm the child, and the parent will wait up for me.\n");
        return 111; // contrived exit status (not a bad number, though)
    } else {
        int status;
        int result = waitpid(pidOrZero, &status, 0);

        // Optional error checking
        if (result != pidOrZero) {
            fprintf(stderr, "Error: waitpid failed\n");
            return kWaitFailed;
        }

        if (WIFEXITED(status)) {
            printf("Child exited with status %d.\n", WEXITSTATUS(status));
        } else {
            printf("Child terminated abnormally.\n");
        }
        return 0;
    }
}
