Building a simple shell #
1use std::io::{self, Write};
2use std::process::{Command, Stdio};
3
4fn main() {
5 loop {
6 // Use the `>` character as the prompt
7 // Need to explicitly flush this to ensure it prints before read_line
8 print!("Shell> ");
9 io::stdout().flush().unwrap();
10
11 let mut input = String::new();
12 io::stdin().read_line(&mut input).expect("Failed to read line");
13
14 let command = input.trim();
15
16 let mut child = Command::new(command)
17 .stdin(Stdio::inherit())
18 .stdout(Stdio::inherit())
19 .stderr(Stdio::inherit())
20 .spawn()
21 .expect("Failed to execute command");
22
23 // Wait for the child process to complete
24 child.wait().expect("Failed to wait for child process");
25 }
26}
**Part by Part explanation:
1 print!("Shell> ");
2 io::stdout().flush().unwrap();
- This code prints a simple shell prompt (
Shell>
) to the standard output and ensures that it is immediately flushed to the console. The.unwrap()
call is used to handle any potential errors during the flushing operation.
1 let mut input = String::new();
2 io::stdin().read_line(&mut input).expect("Failed to read line");
- Here, a mutable
input
variable of typeString
is declared. Theio::stdin().read_line(&mut input)
line reads a line of text from the standard input (keyboard) and stores it in theinput
variable. The.expect()
method is used to handle any errors that may occur during input.
1 let mut child = Command::new(command)
2 .stdin(Stdio::inherit())
3 .stdout(Stdio::inherit())
4 .stderr(Stdio::inherit())
5 .spawn()
6 .expect("Failed to execute command");
-
This code creates a new
Command
with the user's input (thecommand
string) and configures it to inherit the standard input, output, and error streams from the parent process. This allows you to interact with the child process as if you were using a typical shell. -
The
spawn()
method is called to start the child process based on the configured command. The resultingchild
object represents the child process. -
If any errors occur during the process creation, the
.expect()
method handles them and provides an error message.
1 child.wait().expect("Failed to wait for child process");
-
After starting the child process, the program waits for it to complete using
child.wait()
. This blocks the main loop until the child process has finished executing. -
If any errors occur while waiting for the child process to complete, the
.expect()
method provides an error message.
Overall, this Rust program acts as a simple shell that repeatedly accepts user commands, executes them as separate processes, and waits for the processes to complete before accepting the next command. It provides a basic interactive shell-like experience.
Building a Protocol #
Building a deep learning inference system #
ds