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

int main() {
    pid_t pid, wpid;
    int status;

    printf("Parent process started (PID: %d)\n", getpid());

    // Create a child process using fork()
    pid = fork();

    if (pid < 0) {
        // fork failed
        perror("fork failed");
        exit(EXIT_FAILURE);
    } else if (pid == 0) {
        // Child process
        printf("Child process (PID: %d), parent PID: %d\n", getpid(), getppid());

        // Replace the child process with a new program using execl
        printf("Child process will now execute 'ls -l' command\n");
        execl("/bin/ls", "ls", "-l", NULL);

        // If execl returns, it means it failed
        perror("execl failed");
        exit(EXIT_FAILURE);
    } else {
        // Parent process
        printf("Parent process waiting for child (PID: %d) to complete\n", pid);

        // Wait for the child process to complete
        wpid = wait(&status);
        
        if (wpid == -1) {
            perror("wait error");
            exit(EXIT_FAILURE);
        }

        if (WIFEXITED(status)) {
            printf("Child process %d exited with status %d\n", wpid, WEXITSTATUS(status));
        } else if (WIFSIGNALED(status)) {
            printf("Child process %d killed by signal %d\n", wpid, WTERMSIG(status));
        }

        printf("Parent process (PID: %d) exiting\n", getpid());
        exit(EXIT_SUCCESS);
    }
}