Created
September 2, 2023 10:39
-
-
Save timClicks/91c55a7cf08eba91f9804b77c74b4842 to your computer and use it in GitHub Desktop.
Using Rust's MPSC channels to create a system monitoring utility
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[package] | |
name = "tmon" | |
version = "0.1.0" | |
edition = "2021" | |
description = "Code used in this (https://www.youtube.com/live/mVyNAwzj5mA?si=vk-4qPsFlT4x3g6Z) tutorial" | |
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html | |
[dependencies] | |
sysinfo = "0.29" |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// from https://www.youtube.com/live/mVyNAwzj5mA?si=vk-4qPsFlT4x3g6Z | |
use sysinfo; | |
use sysinfo::{System, SystemExt, Component, ComponentExt}; | |
use std::sync::mpsc::channel; | |
use std::thread; | |
enum Request { | |
LoadAvg, | |
Temp, | |
} | |
fn main() { | |
let (req_tx, req_rx) = channel(); | |
let (resp_tx, resp_rx) = channel(); | |
let worker = thread::spawn(move || { | |
let mut sys = System::new_all(); | |
for req in req_rx.iter() { | |
sys.refresh_all(); | |
let msg = match req { | |
Request::LoadAvg => { | |
let load_avg = sys.load_average(); | |
format!( | |
"{{\"one-minute\": {}, \"five-minutes\": {}, \"fifteen-minutes\": {}}}", | |
load_avg.one, | |
load_avg.five, | |
load_avg.fifteen, | |
) | |
}, | |
Request::Temp => { | |
// let mut temp_info = String::new(); | |
let mut coretemps = Vec::new(); | |
for component in sys.components() { | |
if component.label().starts_with("coretemp Core") { | |
let temp = component.temperature(); | |
coretemps.push(temp); | |
} | |
}; | |
// temp_info | |
format!("{coretemps:?}") | |
}, | |
}; | |
resp_tx.send(msg); | |
} | |
}); | |
let printer = thread::spawn(move || { | |
for msg in resp_rx.iter() { | |
println!("{msg}"); | |
} | |
}); | |
loop { | |
req_tx.send(Request::LoadAvg); | |
req_tx.send(Request::Temp); | |
thread::sleep(std::time::Duration::from_secs(1)); | |
} | |
worker.join(); | |
printer.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment