Module std::process 1.0.0[−][src]
Expand description
用于处理进程的模块。
该模块主要与产生和与子进程交互有关,但是它也提供了 abort 和 exit 来终止当前进程。
产生一个进程
Command 结构体用于配置和 spawn 进程:
use std::process::Command; let output = Command::new("echo") .arg("Hello world") .output() .expect("Failed to execute command"); assert_eq!(b"Hello world\n", output.stdout.as_slice());Run
Command 上的几种方法 (例如 spawn 或 output) 可用于 spawn 进程。
特别是,output 生成子进程并等待直到该进程终止,而 spawn 将返回代表生成的子进程的 Child。
处理 I/O
可以通过将 Stdio 传递给 Command 上的相应方法来配置子进程的 stdout,stdin 和 stderr。
生成后,可以从 Child 访问它们。
例如,可以将一个命令的输出管道输送到另一命令,如下所示:
use std::process::{Command, Stdio}; // stdout 必须配置 `Stdio::piped` 才能使用 // `echo_child.stdout` let echo_child = Command::new("echo") .arg("Oh no, a tpyo!") .stdout(Stdio::piped()) .spawn() .expect("Failed to start echo process"); // 请注意,`echo_child` 已移到此处,但我们不再需要 `echo_child` // let echo_out = echo_child.stdout.expect("Failed to open echo stdout"); let mut sed_child = Command::new("sed") .arg("s/tpyo/typo/") .stdin(Stdio::from(echo_out)) .stdout(Stdio::piped()) .spawn() .expect("Failed to start sed process"); let output = sed_child.wait_with_output().expect("Failed to wait on sed"); assert_eq!(b"Oh no, a typo!\n", output.stdout.as_slice());Run
请注意,ChildStderr 和 ChildStdout 实现 Read,而 ChildStdin 实现 Write:
use std::process::{Command, Stdio}; use std::io::Write; let mut child = Command::new("/bin/cat") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() .expect("failed to execute child"); // 如果子进程填充了其 stdout 缓冲区,则它可能最终会等待,直到父进程读取 stdout,并且在此期间无法读取 stdin,从而导致死锁。 // // 从另一个线程进行写入可确保同时读取 stdout,从而避免了该问题。 // // let mut stdin = child.stdin.take().expect("failed to get stdin"); std::thread::spawn(move || { stdin.write_all(b"test").expect("failed to write to stdin"); }); let output = child .wait_with_output() .expect("failed to wait on child"); assert_eq!(b"test", output.stdout.as_slice());Run
Structs
| CommandArgs | Experimental 命令的迭代器。 |
| CommandEnvs | Experimental 命令环境变量上的迭代器。 |
| ExitCode | Experimental 此类型表示进程在正常终止下可以返回其父级的状态代码。 |
| ExitStatusError | Experimental 描述进程失败后的结果 |
| Child | 表示正在运行或退出的子进程。 |
| ChildStderr | 子进程的 stderr 的句柄。 |
| ChildStdin | 子进程的标准输入 (stdin) 的句柄。 |
| ChildStdout | 子进程的标准输出 (stdout) 的句柄。 |
| Command | 进程生成器,提供对如何生成新进程的细粒度控制。 |
| ExitStatus | 描述进程终止后的结果。 |
| Output | 完成的进程的输出。 |
| Stdio | 描述当传递给 |
Traits
| Termination | Experimental trait,用于在 |
Functions
| abort | 以异常方式终止进程。 |
| exit | 使用指定的退出代码终止当前进程。 |
| id | 返回与此进程关联的操作系统分配的进程标识符。 |