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.
  • Loading branch information
jasta committed Mar 20, 2022
1 parent a3ac6df commit 2828ceb
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"]
Expand Down
43 changes: 43 additions & 0 deletions examples/poll_sysfs.rs
Original file line number Diff line number Diff line change
@@ -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(())
}

0 comments on commit 2828ceb

Please sign in to comment.