5 个版本
使用旧的 Rust 2015
0.2.1 | 2018年8月17日 |
---|---|
0.2.0 | 2018年8月17日 |
0.1.2 | 2018年6月6日 |
0.1.1 | 2018年5月4日 |
0.1.0 | 2018年5月4日 |
#62 in #child-process
20KB
315 行
一个简单的crate,允许使用mio处理子进程
用法
extern crate mio_child_process;
extern crate mio;
use mio::{Poll, Token, Ready, PollOpt, Events, Evented};
use std::process::{Command, Stdio};
use mio_child_process::{CommandAsync, ProcessEvent};
use std::sync::mpsc::TryRecvError;
fn main() {
let mut process = Command::new("ping");
if cfg!(target_os = "linux") {
process.arg("-c").arg("4");
}
let mut process = process.arg("8.8.8.8")
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn_async()
.expect("Could not spawn process");
let poll = Poll::new().expect("Could not spawn poll");
let mut events = Events::with_capacity(10);
let token = Token(1);
process.register(&poll, token, Ready::all(), PollOpt::edge()).expect("Could not register");
'outer: loop {
poll.poll(&mut events, None).expect("Could not poll");
for event in &events {
assert_eq!(event.token(), token);
loop {
let result = match process.try_recv() {
Ok(r) => r,
Err(TryRecvError::Empty) => continue,
Err(TryRecvError::Disconnected) => panic!("Could not receive from process"),
};
println!("{:?}", result);
match result {
ProcessEvent::Exit(exit_status) => {
assert!(exit_status.success());
break 'outer;
},
ProcessEvent::IoError(_, _) | ProcessEvent::CommandError(_) => {
assert!(false);
},
_ => {}
}
}
}
}
}
注意
当将 .stdout(Stdio::piped())
传递给 Command
时,才会发出 StdioChannel::Stdout
。
当将 .stderr(Stdio::piped())
传递给 Command
时,才会发出 StdioChannel::Stderr
。
线程
内部为每个监听的 std 流(stdout 和 stderr)创建一个线程。另一个线程会启动,它将处于阻塞等待状态,直到子进程完成。这意味着 mio-child-process 为每个启动的进程使用 1 到 3 个线程。
依赖
~0.7–1MB
~16K SLoC