/**
 * File: spawn-and-cleanup.c
 * --------------------------
 * The following program spawns off a child and
 * then immediately waits on it to finish, and repeats
 * this 8 times.  Each child returns a different
 * exit status.
 */

#include <unistd.h>     // for fork
#include <stdio.h>      // for printf
#include <sys/wait.h>   // for waitpid

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

int main(int argc, char *argv[]) {
    for (size_t i = 0; i < kNumChildren; i++) {
        pid_t pidOrZero = fork();

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

        if (pidOrZero == 0) {
            printf("Hello from child %d!\n", getpid());
            return 111 + i;
        }

        // Only the parent will execute here
        int status;
        pid_t pid = waitpid(pidOrZero, &status, 0);

        // Optional error checking
        if (pid != pidOrZero) {
            fprintf(stderr, "Error: waitpid failed\n");
            return kWaitFailed;
        }
        
        if (WIFEXITED(status)) {
            printf("Child with pid %d exited normally with status %d\n", pid, WEXITSTATUS(status));
        } else {
            printf("Child with pid %d exited abnormally\n", pid);
        }
    }

    return 0;
}
