18.5.1 Pipes
Process
구조체는 실행 중인 하위 프로세스를 나타내고, stdin
, stdout
그리고 stderr
같은 핸들을 공개하여 pipes를 통해 상호작용 한다.
use std::error::Error;
use std::io::prelude::*;
use std::process::{Command, Stdio};
static PANGRAM: &'static str =
"the quick brown fox jumped over the lazy dog\n";
fn main() {
// `wc` 명령을 생성한다.
let process = match Command::new("wc")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn() {
Err(why) => panic!("couldn't spawn wc: {}", why.description()),
Ok(process) => process,
};
// `wc`의 `stdin`에 string을 쓴다.
//
// `stdin`이 소유한 타입 `Option<ChildStdin>`이지만 알다시피 해당 인스턴스는
// 하나만 소유해야 하니까, 바로 `unwrap` 한다.
match process.stdin.unwrap().write_all(PANGRAM.as_bytes()) {
Err(why) => panic!("couldn't write to wc stdin: {}",
why.description()),
Ok(_) => println!("sent pangram to wc"),
}
// `stdin`이 앞의 호출 이후 존재하지 않기에, 이는 `drop`되고,
// pipe는 닫힌다.
//
// 이는 매우 중요한데, 그렇지 않으면 `wc`는
// 우리가 보낸 입력의 처리를 시작하지 않을 것이기 때문이다.
let mut s = String::new();
match process.stdout.unwrap().read_to_string(&mut s) {
Err(why) => panic!("couldn't read wc stdout: {}",
why.description()),
Ok(_) => print!("wc responded with:\n{}", s),
}
}