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?
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).