From 592ddbc2af4d7067ef8825226f85c2271d33eb6d Mon Sep 17 00:00:00 2001 From: Nick Chambers Date: Wed, 27 Dec 2023 15:59:05 -0600 Subject: [PATCH] Add a demonstration of the common fork+exec model --- exec.c | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 exec.c diff --git a/exec.c b/exec.c new file mode 100644 index 0000000..65097d9 --- /dev/null +++ b/exec.c @@ -0,0 +1,40 @@ +#include +#include + +int main() { + // The program that will get run. It is similar to the command-line: + // echo "Hello, world!" + char *const cmdline[] = { "echo", "Hello, world!", NULL }; + + // Create a new process that's a clone of this one. The original process is + // known as the parent, and the new process is known as the child. The child + // process activates in the `fork` call, meaning both the parent and the child + // will return from fork and assign a value to the variable `pid`. + pid_t pid = fork(); + + // When the child process returns from `fork`, the value assigned to `pid` + // will be 0. In the parent process, `pid` will be the process ID (PID) of the + // child process. + if(pid == 0) { + // This call to `exec` will only be run by the child process. This is + // because `exec` replaces the process' instructions with the instructions + // found in `cmdline[0]` (in this case, `echo`). The `v` in `execvp` means + // vector, which in this case refers to the array `cmdline`. The `p` means + // path, indicating that it will search all of the directories found in the + // environment vaiable `PATH` for the program (in this case, `execvp` is + // searching the directories for `echo`). + execvp(cmdline[0], cmdline); + } else { + // In the parent process, pause until the child process exits. The `wait` + // function takes a pointer to a structure that contains information about + // how the child process exited. If the exit information isn't necessary, + // `NULL` can be passed instead. + wait(NULL); + } + + // The parent process is now finished, and will return the number `0` to + // indicate it was successful. The child process will never reach this point + // in this program, since its instructions were replaced with `echo`s + // instructions earlier. + return 0; +}