mini/src/processes.rs

79 lines
2.2 KiB
Rust

use std::fs;
use std::process::{Stdio, Command};
use tokio::process::Command as AsyncCommand;
use tokio::process::Child as AsyncChild;
use std::io::Error;
use tokio;
pub fn get_all_pids() -> Vec<i32> {
let mut pids = Vec::<i32>::new();
let files = fs::read_dir("/proc/").unwrap();
for entry in files {
let path = entry.unwrap().path();
if path.is_dir() {
if let Some(name) = path.file_name() {
let name = name.to_str().unwrap();
match name.parse::<i32>() {
Ok(pid) => {
if pid > 1 {
let content = fs::read_to_string(format!("/proc/{}/cmdline", pid));
match content {
Ok(_) => {
//if cmdline != "" {
pids.push(pid);
//}
},
Err(_) => {}
}
}
},
Err(_) => {}
}
}
}
}
pids
}
pub fn sync_run_wait(path: &str, args: &[&str]) {
let mut child = Command::new(path)
.env("PATH", "/sbin:/bin:/usr/bin")
.args(args)
.spawn()
.unwrap();
child.wait().unwrap();
()
}
async fn _run_cmd(path: &str, args: &[&str]) -> Result<AsyncChild, Error> {
AsyncCommand::new(path)
.env("PATH", "/sbin:/bin:/usr/bin")
.args(args)
.stdout(Stdio::null())
.spawn()
}
// async closures are not supported yet so here's some code duplication that I'll get rid of eventually
pub async fn run(path: &str, args: &[&str]) {
let res = _run_cmd(path, args).await;
match res {
Ok(child) => {
let pid = child.id();
match child.await {
Ok(_) => {},
Err(err) => eprintln!("failed to wait for process with pid {}, error is {}", pid, err)
}
},
Err(err) => eprintln!("could not spawn {}, error is {}", "", err)
}
}