Add a demonstration of the common fork+exec model

This commit is contained in:
Nick Chambers 2023-12-27 15:59:05 -06:00
parent 33a30c82fb
commit 592ddbc2af
1 changed files with 40 additions and 0 deletions

40
exec.c Normal file
View File

@ -0,0 +1,40 @@
#include <sys/wait.h>
#include <unistd.h>
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;
}