Last active
August 29, 2015 14:12
-
-
Save kui/64d9357e9b91f8f149e4 to your computer and use it in GitHub Desktop.
example which invoke external process
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 外部プロセス呼び出しサンプル | |
// 外部プロセスの標準出力・エラー出力はこのプロセスのものを使う | |
extern crate libc; | |
use std::io::{Command, IoResult}; | |
use std::io::process::ProcessExit; | |
use std::io::process::ProcessExit::{ExitStatus, ExitSignal}; | |
use std::io::process::StdioContainer::InheritFd; | |
// POSIX 以外だとどうなる? | |
use libc::consts::os::posix88::{STDOUT_FILENO, STDERR_FILENO}; | |
fn main() { | |
//match exec("sleep", &["10000"], 1000) { // long running process | |
//match exec("foo", &[], 1000) { // invalid command | |
//match exec("cat", &["foo"], 1000) { // error exit command | |
match exec("echo", &["foo", "bar"], 1000) { // valid command | |
Ok(ExitStatus(s)) => println!("exit: {}", s), | |
Ok(ExitSignal(s)) => println!("received signal: {}", s), | |
Err(_) => panic!("timeout"), | |
} | |
} | |
fn exec(prog: &str, args: &[&str], timeout: u64) -> IoResult<ProcessExit> { | |
let mut c = Command::new(prog); | |
c.args(args) | |
.stdout(InheritFd(STDOUT_FILENO)) | |
.stderr(InheritFd(STDERR_FILENO)); | |
let mut p = try!(c.spawn()); | |
p.set_timeout(Some(timeout)); | |
let r = p.wait(); | |
if r.is_err() { | |
let _ = p.signal_kill(); | |
} | |
r | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment