/**
 * File: not-so-random.c
 * --------------------
 * This program emphasizes the state that is copied from
 * a parent to its child when forking.  Both the parent
 * and the child execute random() below - what are the outcomes
 * in each case?
 */

#include <stdbool.h>  // for bool
#include <stdlib.h>   // for exit, srandom, random
#include <unistd.h>   // for fork
#include <stdio.h>    // for printf, etc
#include <sys/wait.h> // for waitpid
#include <time.h>     // for time
#include "exit-utils.h"

static const int kForkFailure = 1;

int main(int argc, char *argv[]) {
    // Initialize the random number with a "seed value"
    // this seed state is used to generate future random numbers
    srandom(time(NULL));

    printf("I'm unique and just get printed once.\n");
    pid_t pidOrZero = fork();
    exitIf(pidOrZero == -1, kForkFailure, stderr, "Call to fork failed... aborting.\n");

    // force exactly one of the two to sleep (why exactly one?)
    bool isParent = pidOrZero != 0;
    int result = random() % 2;
    if ((result == 0) == isParent) {
        sleep(1); 
    }
  
    printf("I get printed twice (this one is being printed from the %s).\n", isParent  ? "parent" : "child");
    return 0;
}
