This shell in C is written by following Stephen Brennan’s tutorial, with a few additional functionalities such as managing and listing background processes and handling output redirection.
This is a small program that lets you run other programs and a few basic commands from your terminal. Here's a simple overview of its operation:
-
Reads and Parses Commands: LSH waits for your input, then breaks it down into the command name and any arguments.
-
Decides Execution Method:
- Built-in Commands: For commands like
cd,help,lsps, orexit, LSH executes them directly within itself. These commands are vital for changing the shell's own state (e.g., its current directory). - External Programs: For other commands (like
lsorgrep), LSH launches them as separate "external programs."
- Built-in Commands: For commands like
When you type an external command (e.g., ls -l), LSH follows these steps:
-
Creates a Copy (
fork()): LSH uses thefork()command to create an exact duplicate of itself. Now, two identical LSH processes are running: the original (parent) and the new copy (child). -
Transforms the Copy (
execvp()): The child process immediately usesexecvp(). This command tells the operating system to stop running the LSH code in the child and, instead, load and start the new program (lsin this example) in its place. The child process effectively becomes thelsprogram. -
Parent Waits (
waitpid()): While the child process runs the external program, the original LSH shell (the "parent" process) pauses its own execution. It useswaitpid()to wait until the child process finishes. -
Child Finishes, LSH Continues: Once the external program completes, the child process terminates. The original LSH shell detects this, resumes execution, and displays a new prompt (
>), ready for your next command.
In essence, LSH launches external programs by duplicating itself, transforming that copy into the desired program, and then waiting for that program to complete.