Compare commits

...

2 Commits

3 changed files with 42 additions and 2 deletions

View File

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2023 uplime
Copyright (c) 2023 Nick Chambers <uplime@spookyinternet.com>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

View File

@ -1,3 +1,3 @@
# shellfish
Examples demonstrating how command-line shells implement features.
Examples demonstrating how command-line shells implement features.

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;
}