In this lesson, you will learn how your command line transforms from a simple line of text into a running program inside your computer's memory.
The Life of a Command
When you type a command into your terminal—like ls—and press Enter, the shell performs a rapid three-step dance to make that command come alive.
1. Parsing
The shell first acts like a translator. It looks at the text you typed, breaks it down into individual words, and identifies the command name and its arguments. It also handles "expansions," like turning a * into a list of files. Think of this as the shell checking the syntax of your request to ensure it understands what you want to execute.
2. Forking
This is the moment of creation. The shell needs to run your command without closing itself down. To do this, it performs a fork. Imagine the shell cloning itself; it creates an exact copy of its own process. This new copy is called the "child process." The shell (the "parent") pauses and waits, while the child process prepares to take over.
3. Execution
Now, the child process performs the "exec" step. It reaches into the operating system’s storage, finds the program you requested (like ls), and loads it into memory, completely replacing its own current identity with that of the new program. The kernel then begins running that program. Once the program finishes its work, it signals the shell, the child process dies, and the shell wakes up to give you your prompt back.
A Quick Illustration
If you type ls, the process looks like this:
User input: "ls"
1. Shell parses "ls".
2. Shell forks (creates a clone).
3. Child process executes "ls" binary.
4. "ls" runs, displays files, and exits.
5. Shell returns the prompt to you.
By using this "Fork and Exec" model, the shell ensures that even if a program crashes, your terminal remains stable and ready for your next command.
Key Takeaway: The shell executes commands by parsing your input, forking a child process, and replacing that process with the target program to be run by the kernel.