#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>


int main(int argc, char **argv) {

    //iterations is an integer that stores 
    //the number of iterations the program will run
    int loopval, iterations;

    if (argc != 2) {
        fprintf(stderr, "Usage: forkloop <iterations>\n");
        exit(1);
    }

	int forked;
    //iterations is set to the integer representation of the 
    //command line argument (the second element of the array argv)
    iterations = strtol(argv[1], NULL, 10);

    for (loopval = 0; loopval < iterations; 
    loopval++) {
		//Fork once for the parent
		if(loopval == 0){
			forked = fork();
		    if(forked < 0) {
				perror("fork");
				exit(1);
			}
		}
		else{
			//Fork once per child
			if(forked == 0){
				forked = fork();
				if(forked < 0) {
					perror("fork");
					exit(1);
				}
			}
		}

        printf("ppid = %d, pid = %d, i = %d\n", getppid(), getpid(), i);
    }

    return 0;
}