rust 如何交织shell提示符和子进程输出,理想情况下只使用std?

eqoofvh9  于 4个月前  发布在  Shell
关注(0)|答案(1)|浏览(64)

我正在尝试将我的OS项目重新创建到Rust中,目前我遇到了一个风格问题,我正在尝试创建一个非常简单的shell,它接受一个输入并执行一个命令。我的问题是,当使用:

print!("tsh> ");
let mut input: String = String::new();
let _ = io::stdout().flush(); // allows to print then stdinio::stdin().read_line(&mut input).expect("Error: Expected input");

字符串
然后,当命令执行时,输出看起来像这样:

tsh> ls .
tsh> Cargo.lock  Cargo.toml     src  target


在第二个tsh>..下面输入
我非常喜欢只在我能够使用的地方使用标准库,只是因为这是一个有趣的挑战,而且这似乎是我应该做的,因为原始版本是基于C++标准库的。下面是代码的最小版本:

use std::io::{self,Write};
use std::process::Command;

fn main() {
    loop {
        print!("tsh> ");
        let mut input: String = String::new();
        let _ = io::stdout().flush(); // allows to print then stdin
        io::stdin().read_line(&mut input).expect("Error: Expected input");
        
        if &input != "\n" {
            let tokens: Vec<&str> = input.split_whitespace().collect();
            let output = Command::new(tokens[0].to_string())
                .arg(tokens[1..].join(" "))
                .spawn()
                .expect("Error: Failed to execute command");
        }
    }
}

zvokhttg

zvokhttg1#

子进程与程序并行执行。添加对wait的调用以等待它们完成,然后显示下一个提示符。

let _exit_status = Command::new(tokens[0].to_string())
    .arg(tokens[1..].join(" "))
    .spawn()
    .expect("Error: Failed to execute command")
    .wait()
    .expect("Error: Failed to execute command");

字符串

相关问题