/* =============================================================================
 * 04_exec.c -- fork + execve + wait: how a shell launches a program
 * =============================================================================
 *
 * [Idea]
 *   fork() makes a copy of the CURRENT program. To run a DIFFERENT program you
 *   fork, and then in the child call one of the exec functions, which REPLACES
 *   the child's entire memory image with a new program loaded from disk. The
 *   call does not return on success -- there is nothing to return to, the old
 *   code is gone. This fork-then-exec pair is exactly how a shell runs a
 *   command: fork a child, exec the command in it, and wait() for it.
 *
 *   We launch "/bin/echo" with two arguments and wait for it. The line printed
 *   AFTER execve in the child never appears, because a successful execve wipes
 *   out the code that would have printed it.
 *
 * [What it answers]
 *   - What is the difference between fork (copy me) and exec (become someone else)?
 *   - Why does code after a successful exec never run?
 *   - How do argv[] and envp[] reach the new program?
 *
 * Build & run:    make run
 * -----------------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>

extern char **environ;  /* the current environment, passed on to the new program */

int main(void)
{
    printf("[parent] pid=%d; about to fork+exec /bin/echo\n", getpid());
    fflush(stdout);

    pid_t pid = fork();
    if (pid < 0) { perror("fork"); return 1; }

    if (pid == 0) {
        /* -------- child: become a completely different program -------- */
        /* argv must be NULL-terminated; argv[0] is conventionally the program
           name. These two words are what /bin/echo will print. */
        char *argv[] = { "/bin/echo", "hello", "from execve", NULL };
        execve(argv[0], argv, environ);
        /* If we get here, execve FAILED (bad path, no permission, ...). On
           success this line is unreachable: the echo program has taken over. */
        perror("execve");
        _exit(127);
    }

    /* -------- parent: wait for the child (the launched program) to finish -- */
    int status;
    waitpid(pid, &status, 0);
    if (WIFEXITED(status))
        printf("[parent] child (/bin/echo) exited with status %d\n",
               WEXITSTATUS(status));
    else
        printf("[parent] child did not exit normally\n");

    printf("[parent] note: the child never printed anything of its OWN after\n"
           "         execve -- its old code was replaced by /bin/echo\n");
    return 0;
}

/*
 * Observations (author's machine, Apple M4 Pro, macOS):
 *   [parent] pid=P; about to fork+exec /bin/echo
 *   hello from execve                 <- printed by /bin/echo, the new image
 *   [parent] child (/bin/echo) exited with status 0
 *   [parent] note: the child never printed anything of its OWN after execve...
 *
 *   - "hello from execve" is produced by the echo PROGRAM, running in the
 *     child's process. Our own C code in the child after execve did not run.
 *   - fork duplicates; exec replaces. A shell command = fork + exec + wait.
 *   - argv[1..] became echo's words; environ was carried into the new program.
 */
