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

int main() {
    pid_t pid;

    printf("Starting program (PID: %d)\n", getpid());

    // fork() system call to create a new process
    pid = fork();

    if (pid < 0) {
        // Error occurred
        fprintf(stderr, "Fork Failed\n");
        return 1;
    }
    else if (pid == 0) {
        // Child Process
        printf("\n[Child] Created (PID: %d)\n", getpid());
        printf("[Child] Parent PID: %d\n", getppid());
        printf("[Child] Performing task and exiting...\n");
        sleep(2); // Simulate work
        exit(0); // Exit system call
    }
    else {
        // Parent Process
        printf("\n[Parent] Created child with PID: %d\n", pid);
        printf("[Parent] Waiting for child to finish...\n");
        
        // wait() system call to wait for child completion
        wait(NULL); 
        
        printf("\n[Parent] Child finished.\n");
        printf("[Parent] Exiting.\n");
    }

    return 0;
}
