当前位置:   article > 正文

rust运行shell命令并获取输出_rust 执行shell

rust 执行shell
use std::io::{BufReader, BufRead};
use std::process::{self, Command, Stdio};

fn main() {
    ls();
    ps();
    xargs();
    time();
    iostat();
}

// 不带参数命令
fn ls() {
    let output = Command::new("ls").output().expect("执行异常,提示");
    let out = String::from_utf8(output.stdout).unwrap();
    println!("{}", out);
}

// 带参数命令
fn ps() {
    // ps -q $$ -o %cpu,%mem
    let output = Command::new("ps")
        .arg("-q")
        .arg(process::id().to_string())
        .arg("-o")
        .arg("%cpu,%mem")
        .output()
        .unwrap();
    let out = String::from_utf8(output.stdout).unwrap();
    println!("{}", out);
}

// 复杂命令,直接扔进bash执行
fn xargs() {
    let mut cmd = "cat /proc/".to_string();
    cmd += &process::id().to_string();
    cmd += &"/stat | awk '{print $14,$15,$16,$17}'".to_string();
    let output = Command::new("bash")
        .arg("-c")
        .arg(cmd)
        .output()
        .unwrap();
    let out = String::from_utf8(output.stdout).unwrap();
    println!("utime stime cutime cstime");
    println!("{}", out);
}

// 手动实现管道
fn time() {
    let mut fname = "/proc/".to_string();
    fname += &process::id().to_string();
    fname += &"/stat".to_string();
    let child = Command::new("cat")
        .arg(fname)
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let output = Command::new("awk")
        .arg("{print $14,$15,$16,$17}")
        .stdin(child.stdout.unwrap())
        .output()
        .unwrap();
    let out = String::from_utf8(output.stdout).unwrap();
    println!("utime stime cutime cstime");
    println!("{}", out);
}

// 获取运行中的命令的输出
fn iostat() {
    let child = Command::new("iostat")
        .arg("1")
        .stdout(Stdio::piped())
        .spawn()
        .unwrap();
    let mut out = BufReader::new(child.stdout.unwrap());
    let mut line = String::new();
    while let Ok(_) = out.read_line(&mut line) {
        println!("{}", line);
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80

参考文献:

rust:执行shell命令
https://stackoverflow.com/questions/40836973/unable-to-use-stdprocesscommand-no-such-file-or-directory
https://www.reddit.com/r/rust/comments/3azfie/how_to_pipe_one_process_into_another/

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/951251
推荐阅读
相关标签
  

闽ICP备14008679号