smol/examples/linux-inotify.rs

59 lines
1.6 KiB
Rust
Raw Normal View History

2020-04-26 17:37:29 +00:00
//! Uses the `inotify` crate to watch for changes in the current directory.
//!
//! Run with:
//!
//! ```
//! cargo run --example linux-inotify
//! ```
2020-04-02 14:44:49 +00:00
#[cfg(target_os = "linux")]
fn main() -> std::io::Result<()> {
use std::ffi::OsString;
use inotify::{EventMask, Inotify, WatchMask};
2020-07-23 10:24:16 +00:00
use smol::{io, Async};
2020-04-02 14:44:49 +00:00
type Event = (OsString, EventMask);
/// Reads some events without blocking.
2020-04-26 17:37:29 +00:00
///
/// If there are no events, an [`io::ErrorKind::WouldBlock`] error is returned.
2020-04-08 21:51:52 +00:00
fn read_op(inotify: &mut Inotify) -> io::Result<Vec<Event>> {
2020-04-02 14:44:49 +00:00
let mut buffer = [0; 1024];
let events = inotify
.read_events(&mut buffer)?
.filter_map(|ev| ev.name.map(|name| (name.to_owned(), ev.mask)))
.collect::<Vec<_>>();
if events.is_empty() {
2020-04-12 13:02:42 +00:00
Err(io::ErrorKind::WouldBlock.into())
2020-04-02 14:44:49 +00:00
} else {
Ok(events)
}
}
2020-08-26 21:59:49 +00:00
smol::block_on(async {
2020-04-02 14:44:49 +00:00
// Watch events in the current directory.
let mut inotify = Async::new(Inotify::init()?)?;
inotify
.get_mut()
.watches()
.add(".", WatchMask::ALL_EVENTS)?;
2020-04-02 14:44:49 +00:00
println!("Watching for filesystem events in the current directory...");
2020-04-26 17:37:29 +00:00
println!("Try opening a file to trigger some events.");
println!();
2020-04-02 14:44:49 +00:00
2020-04-26 17:37:29 +00:00
// Wait for events in a loop and print them on the screen.
2020-04-02 14:44:49 +00:00
loop {
for event in inotify.read_with_mut(read_op).await? {
2020-04-02 14:44:49 +00:00
println!("{:?}", event);
}
}
})
}
#[cfg(not(target_os = "linux"))]
fn main() {
println!("This example works only on Linux!");
}