From 2828cebdea1b6e191e478cecaad4d343a589ebd1 Mon Sep 17 00:00:00 2001 From: jasta Date: Sat, 19 Mar 2022 21:10:10 -0700 Subject: [PATCH] Add example of new PollWatcher compare_contents feature The example shows how to use this to effectively watch pseudo filesystems like those through sysfs (i.e. /sys/). The example by default will only work on Linux but does demonstrate well that it works where the previous metadata only approach would not. --- Cargo.toml | 1 + examples/poll_sysfs.rs | 43 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 examples/poll_sysfs.rs diff --git a/Cargo.toml b/Cargo.toml index f687e975..09498297 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -50,6 +50,7 @@ futures = "0.3" serde_json = "1.0.39" tempfile = "3.2.0" nix = "0.23.1" +glob = "0.3.0" [features] default = ["macos_fsevent"] diff --git a/examples/poll_sysfs.rs b/examples/poll_sysfs.rs new file mode 100644 index 00000000..f161bf3e --- /dev/null +++ b/examples/poll_sysfs.rs @@ -0,0 +1,43 @@ +use std::path::Path; +use std::time::Duration; +use notify::poll::PollWatcherConfig; +use notify::{PollWatcher, RecursiveMode, Watcher}; +use glob::glob; + +fn main() -> notify::Result<()> { + let mut paths: Vec<_> = std::env::args().skip(1) + .map(|arg| Path::new(&arg).to_path_buf()) + .collect(); + if paths.is_empty() { + let interfaces = glob("/sys/class/net/*/statistics") + .map_err(|e| notify::Error::generic(&e.to_string()))? + .filter_map(|result| result.ok()); + paths.extend(interfaces); + } + + if paths.is_empty() { + eprintln!("Must provide path to watch, default system paths in /sys/class/net were not found (maybe you're not running on Linux?)"); + std::process::exit(1); + } + + println!("watching {:?}...", paths); + + let config = PollWatcherConfig { + compare_contents: true, + poll_interval: Duration::from_secs(2), + }; + let (tx, rx) = std::sync::mpsc::channel(); + let mut watcher = PollWatcher::with_config(tx, config)?; + for path in paths { + watcher.watch(&path, RecursiveMode::Recursive)?; + } + + for res in rx { + match res { + Ok(event) => println!("changed: {:?}", event), + Err(e) => println!("watch error: {:?}", e), + } + } + + Ok(()) +}