パイプ

The std::process::Child struct represents a child process, and exposes the stdin, stdout and stderr handles for interaction with the underlying process via pipes.

use std::io::prelude::*; use std::process::{Command, Stdio}; static PANGRAM: &'static str = "the quick brown fox jumps over the lazy dog\n"; fn main() { // `wc`コマンドを起動します。 let mut cmd = if cfg!(target_family = "windows") { let mut cmd = Command::new("powershell"); cmd.arg("-Command").arg("$input | Measure-Object -Line -Word -Character"); cmd } else { Command::new("wc") }; let process = match cmd .stdin(Stdio::piped()) .stdout(Stdio::piped()) .spawn() { Err(why) => panic!("couldn't spawn wc: {}", why), Ok(process) => process, }; // `wc`の`stdin`に文字列を書き込みます。 // // `stdin`は`Option<ChildStdin>`型を持ちますが、今回は値を持っていることが // 確かなので、いきなり`unwrap`してしまって構いません。 match process.stdin.unwrap().write_all(PANGRAM.as_bytes()) { Err(why) => panic!("couldn't write to wc stdin: {}", why), Ok(_) => println!("sent pangram to wc"), } // `stdin`は上のプロセスコールのあとには有効でないので、`drop`され、 // パイプはcloseされます。 // // これは非常に重要です。というのもcloseしないと`wc`は // 送った値の処理を開始しないからです。 // `stdout`フィールドも`Option<ChildStdout>`型なのでアンラップする必要があります let mut s = String::new(); match process.stdout.unwrap().read_to_string(&mut s) { Err(why) => panic!("couldn't read wc stdout: {}", why), Ok(_) => print!("wc responded with:\n{}", s), } }