process - 执行任何 bash 命令,立即获取 stdout/stderr 的结果并使用 stdin

标签 process rust output exec

我想执行任何 bash 命令。我找到了 Command::new 但我无法执行诸如 ls 之类的“复杂”命令; sleep 1; ls。此外,即使我将它放在 bash 脚本中并执行它,我也只会在脚本末尾得到结果(如流程文档中所述)。我希望在命令打印结果后立即获得结果(并且能够读取输入),就像我们在 bash 中那样。

最佳答案

Command::new 确实是要走的路,但它是为了执行程序。 ls; sleep 1; ls 不是一个程序,它是一些 shell 的指令。如果您想执行类似的操作,您需要让 shell 为您解释:

Command::new("/usr/bin/sh").args(&["-c", "ls ; sleep 1; ls"])
// your complex command is just an argument for the shell

获取输出有两种方式:

  • output方法正在阻塞并返回命令的输出和退出状态。
  • spawn方法是非阻塞的,并返回一个包含子进程 stdinstdoutstderr 的句柄,以便您可以与子进程通信,以及wait等待它干净退出的方法。请注意,默认情况下,子级继承其父级文件描述符,您可能希望改为设置管道:

你应该使用类似的东西:

let child = Command::new("/usr/bin/sh")
                .args(&["-c", "ls  sleep 1 ls"])
                .stderr(std::process::Stdio::null()) // don't care about stderr
                .stdout(std::process::Stdio::piped()) // set up stdout so we can read it
                .stdin(std::process::Stdio::piped()) // set up stdin so we can write on it
                .spawn().expect("Could not run the command"); // finally run the command

write_something_on(child.stdin);
read(child.stdout);

关于process - 执行任何 bash 命令,立即获取 stdout/stderr 的结果并使用 stdin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50612937/

相关文章:

c# - CreateProcessWithTokenW winapi 返回 false 但没有原因

c - 通过管道从一个进程发送到另一个进程的缓冲区大小

vector - 是否有一种简单的方法可以从 `Vec` 中准确提取一个元素?

java - 方法返回不正确的值?

python - pandas value_counts 输出文件

c++ - 奇怪的家长 ID

c - 使用 GetMessage 接收消息结构类型,然后分配给另一个相同的结构

Rust 中的 Unix 选择系统调用

rust - 解决通过引用获取参数的闭包的类型不匹配

Hadoop - 将 reducer 编号设置为 0 但写入同一文件?