Newbie question about calling the top command from rust

So basically, I am trying to write a program that checks which apps and or processes are open. How might I call the top command, then terminate the top command after a few seconds, so I can actually return the output?

pub fn checkapps() -> std::process::Output {
    let openapps = Command::new("sh")
       .arg("-c")
       .arg("top")
       .output()
       .expect("failed to execute process");
    return openapps;
}

This function never actually returns, because the top command goes on indefinitely. How do I fix this?

Running with the -l1 flag (that's a lowercase L and a numeral one) will cause top to terminate after one sample.

1 Like
use std::process::Command;

fn main() -> Result<(), std::io::Error> {
    let out = String::from_utf8(
        Command::new("top")
        .arg("-n1")
        .arg("-b")
        .output()?
        .stdout
    ).expect("invalid output from top");

    println!("{}", out);
    Ok(())
}

in addition to what @mbrubeck said, for me -b was also necessary for top to be run from inside the application. note that you can spawn top directly without using the shell (sh).

2 Likes

Is there any way I can limit the number of columns and rows of the output? using .arg("COLUMNS=8") does not work.

Looks like top expects COLUMNS as an environment variable. Looks like you want

.env("COLUMNS", "8")
1 Like