/*    main program illustrating the UNIX fork() system call. 
Compile using cc -o main main.c
*/
#include <stdio.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main() {
    pid_t pid1 = 0, pid2 = 0, pid3 = 0, pid4 = 0, pid5 = 0, pid6 = 0;

    pid1 = fork();
    printf("pid1 has been executed!");
    if (pid1 == 0) {  // Child process
        pid2 = fork();
        printf("A");
        printf("pid2 has been executed!");
        printf("Process %d created, Parent: %d\n", getpid(), getppid());
    } else {  // Parent process executes execvp
        char *args[] = {"/bin/ls", NULL};
        execvp(args[0], args);
    }

    printf("Process %d created, Parent: %d\n", getpid(), getppid());
    printf("B");
    pid3 = fork();
    if (pid4 != 0) {  // Parent process
    	printf("C");
        printf("Process %d created, Parent: %d\n", getpid(), getppid());
        char *args[] = {"/bin/ls", NULL};
        execvp(args[0], args);
    } else {  // Child process
        if (pid1 != 0) {  // If this is not the first child
            pid5 = fork();
            printf("Process %d created, Parent: %d\n", getpid(), getppid());
            char *args[] = {"/bin/ls", NULL};
            execvp(args[0], args);
            printf("D");
        }
    }

    if (pid2 > 0) {  // Only for the original parent process
        pid6 = fork();
        printf("E");
        printf("Process %d created, Parent: %d\n", getpid(), getppid());
    } else {  // pid2 == 0 case
    	printf("F");
        printf("Process %d created, Parent: %d\n", getpid(), getppid());
        char *args[] = {"/bin/ls", NULL};
        execvp(args[0], args);
    }
    
    printf("G");

    printf("Process %d created, Parent: %d\n", getpid(), getppid());

    return 0;
}