use std::process::Command;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::Duration;
use anyhow::Result;
use fcache::prelude::*;
use signal_hook::consts::SIGINT;
use signal_hook::iterator::Signals;
fn main() -> Result<()> {
let running = Arc::new(AtomicBool::new(true));
let mut signals = Signals::new([SIGINT])?;
{
let running = Arc::clone(&running);
thread::spawn(move || {
if signals.forever().next().is_some() {
running.store(false, Ordering::SeqCst);
}
});
}
println!("You should observe the uptime of the system being printed every second.");
println!("The output changes every 5 seconds due to cache interval. Press Ctrl+C to stop.");
thread::sleep(Duration::from_secs(5));
println!();
let cache = fcache::new()?;
let file = {
cache.get_lazy("uptime", move |mut file| {
let uptime = Command::new("uptime").output()?;
file.write_all(&uptime.stdout)?;
Ok(())
})?
};
if file.path().exists() {
anyhow::bail!("Lazy file should not exist");
}
while running.load(Ordering::SeqCst) {
let mut content = String::new();
file.open()?.read_to_string(&mut content)?;
print!("Uptime: {content}");
thread::sleep(Duration::from_secs(1));
}
println!("Program terminated gracefully.");
Ok(())
}