rcmd_core/util/
shcmd.rs

1use std::process::{Command, Stdio};
2
3///执行系统命令
4pub fn run_sh(cmd: &str, arg: &Vec<&str>) -> (bool, String) {
5    println!("run cmd bin:{}\n", cmd);
6    println!("args is :{:?}\n", arg);
7    let child = Command::new(cmd)
8        .args(arg)
9        .output()
10        .expect("failed to execute child");
11    let ret = String::from_utf8_lossy(&child.stdout).into_owned();
12    if child.status.success() {
13        return (true, ret);
14    }
15    println!("{}", String::from_utf8_lossy(&child.stdout).into_owned());
16    return (false, String::from_utf8_lossy(&child.stderr).into_owned());
17}
18
19///同步执行系统命令(todo)
20pub fn run_sh_async(cmd: &String, arg: &Vec<&str>) -> (bool, String) {
21    println!("run cmd bin:{}\n", cmd);
22    println!("args is :{:?}\n", arg);
23    let child = Command::new(cmd)
24        .args(arg)
25        .stdout(Stdio::piped())
26        .spawn()
27        .expect("failed to execute child");
28
29    let output = child
30        .wait_with_output()
31        .expect("failed to wait on child");
32    let ret = String::from_utf8_lossy(&output.stdout).into_owned();
33    if output.status.success() {
34        return (true, ret);
35    }
36    return (false, String::from_utf8_lossy(&output.stderr).into_owned());
37}