Skip to content

Commit

Permalink
Add example of new PollWatcher compare_contents feature
Browse files Browse the repository at this point in the history
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.

Sample output:

  Trying "/sys/class/net/lo/statistics/tx_bytes", use `ping localhost` to see changes!
  watching ["/sys/class/net/lo/statistics/tx_bytes"]...
  changed: Event { kind: Modify(Data(Any)), paths: ["/sys/class/net/lo/statistics/tx_bytes"], attr:tracker: None, attr:flag: None, attr:info: None, attr:source: None }
  changed: Event { kind: Modify(Data(Any)), paths: ["/sys/class/net/lo/statistics/tx_bytes"], attr:tracker: None, attr:flag: None, attr:info: None, attr:source: None }
  changed: Event { kind: Modify(Data(Any)), paths: ["/sys/class/net/lo/statistics/tx_bytes"], attr:tracker: None, attr:flag: None, attr:info: None, attr:source: None }
  changed: Event { kind: Modify(Data(Any)), paths: ["/sys/class/net/lo/statistics/tx_bytes"], attr:tracker: None, attr:flag: None, attr:info: None, attr:source: None }
  • Loading branch information
jasta committed Mar 20, 2022
1 parent a3ac6df commit 738cbce
Showing 1 changed file with 40 additions and 0 deletions.
40 changes: 40 additions & 0 deletions examples/poll_sysfs.rs
@@ -0,0 +1,40 @@
use std::path::Path;
use std::time::Duration;
use notify::poll::PollWatcherConfig;
use notify::{PollWatcher, RecursiveMode, Watcher};

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 lo_stats = Path::new("/sys/class/net/lo/statistics/tx_bytes").to_path_buf();
if !lo_stats.exists() {
eprintln!("Must provide path to watch, default system path was not found (probably you're not running on Linux?)");
std::process::exit(1);
}
println!("Trying {lo_stats:?}, use `ping localhost` to see changes!");
paths.push(lo_stats);
}

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(())
}

0 comments on commit 738cbce

Please sign in to comment.