Skip to main content

add_watch

Function add_watch 

Source
pub fn add_watch(fd: &Fd, path: &str, mask: u32) -> Result<i32, CoreError>
Expand description

Add a watch to an existing inotify instance.

§Arguments

  • fd - The inotify file descriptor.
  • path - Path to the file or directory to watch.
  • mask - Events to monitor (e.g., MODIFY_MASK).

§Errors

Returns CoreError if inotify_add_watch fails or if the path contains a NUL byte.

Examples found in repository?
examples/watch_temp.rs (line 13)
5fn main() -> Result<(), Box<dyn std::error::Error>> {
6    let mut reactor = Reactor::new()?;
7    let (inotify_fd, inotify_token) = reactor.setup_inotify()?;
8
9    let temp_dir = std::env::temp_dir();
10    let temp_dir_str = temp_dir.to_string_lossy().into_owned();
11
12    println!("Watching {} for modifications...", temp_dir_str);
13    add_watch(&inotify_fd, &temp_dir_str, MODIFY_MASK)?;
14
15    let mut events = Vec::new();
16    // Monitor for 10 seconds
17    let start = std::time::Instant::now();
18    while start.elapsed() < Duration::from_secs(10) {
19        let n = reactor.wait(&mut events, 64, 1000)?;
20        if n > 0 {
21            for ev in &events {
22                if ev.token == inotify_token {
23                    let in_events = read_events(&inotify_fd)?;
24                    for ie in in_events {
25                        if let Some(name) = ie.name {
26                            println!("File modified: {}", String::from_utf8_lossy(&name));
27                        } else {
28                            println!("Directory modified (wd={})", ie.wd);
29                        }
30                    }
31                }
32            }
33        }
34    }
35
36    println!("Finished watching.");
37    Ok(())
38}