@electricface
2014-04-17T08:52:11.000000Z
字数 2671
阅读 2473
库 std::io::Process
pub struct Process {
stdin: Option<PipeStream>,
stdout: Option<PipeStream>,
stderr: Option<PipeStream>,
extra_io: ~[Option<PipeStream>],
// some fields omitted
}
use std::io::Process;
fn main(){
let mut child = match Process::new("cat" , [~"abc.rs.."]){
Ok(child) => child,
Err(e) => fail!("failed to execute child: {}",e)
};
let contents = child.stdout.get_mut_ref().read_to_str().unwrap();
println!( "Cotents: {}", contents);
if ! child.wait().success() {
let err_info = child.stderr.get_mut_ref().read_to_str().unwrap() ;
println!( "ERROR: {}", err_info);
}
}
fn new(prog: &str, args: &[~str]) -> IoResult<Process>
prog 命令地址
args 参数
type IoResult<T> = Result<T, IoError>;
关心 输入输出
use std::io::Process;
use std::str;
fn main(){
let output = match Process::output("cat",[~"abc.rs"]) {
Ok(o) => o,
Err(e) => fail!("failed to execute process: {}",e),
};
println!("status: {}",output.status);
println!("OUT: {}",str::from_utf8_lossy(output.output) );
println!("ERROR: {}",str::from_utf8_lossy(output.error) );
}
将 [u8] 转换为 MaybeOwened<’a>
pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> MaybeOwned<'a>
//枚举 MaybeOwned<'a> 它可以同时放 ~str 和 &str
pub enum MaybeOwned<'a> {
Slice(&'a str),
Owned(~str),
}
fn is_owned(&self) -> bool
fn into_owned(self) -> ~str
fn is_slice(&self) -> bool
fn as_slice<'b>(&'b self) -> &'b str
//实现了 Show 特性,可用 println!() 输出
pub struct ProcessOutput {
status: ProcessExit,
output: ~[u8],
error: ~[u8],
}
pub enum ProcessExit {
ExitStatus(int),
ExitSignal(int),
}
//是否成功
fn success(&self) -> bool
//是否匹配退出状态
fn matches_exit_status(&self, wanted: int) -> bool
只关心退出状态
use std::io::Process;
fn main(){
let status = match Process::status("ls",[~".."]) {
Ok(status) => status,
Err(e) => fail!("failed to execute process: {}",e )
};
if status.success() {
println!("good end");
} else {
println!( "ERROR: process exited with: {}" , status );
}
}
use std::io::{ProcessConfig,Process};
use std::str::from_utf8_lossy;
fn main(){
let config = ProcessConfig {
program: "/bin/sh",
args: &[~"-c", ~"echo 123+345|bc"],
.. ProcessConfig::new()
};
let mut child = match Process::configure(config){
Ok(o) => o,
Err(e) => fail!("failed to execute process: {}",e)
};
let output = child.wait_with_output().output;
println!("OUT: {}" , from_utf8_lossy( output) );
}
pub struct ProcessConfig<'a> {
program: &'a str,
args: &'a [~str],
env: Option<&'a [(~str, ~str)]>,
cwd: Option<&'a Path>,
stdin: StdioContainer,
stdout: StdioContainer,
stderr: StdioContainer,
extra_io: &'a [StdioContainer],
uid: Option<uint>,
gid: Option<uint>,
detach: bool,
}
fn kill(id: pid_t, signal: int) -> IoResult<()>
fn id(&self) -> pid_t
fn signal(&mut self, signal: int) -> IoResult<()>
fn signal_exit(&mut self) -> IoResult<()>
fn signal_kill(&mut self) -> IoResult<()>
fn wait(&mut self) -> ProcessExit
fn wait_with_output(&mut self) -> ProcessOutput