Crate notify
Cross-platform file system notification library
Installation
[dependencies]
notify = "9.0.0"
If you want debounced events (or don't need them in-order), see notify-debouncer-mini or notify-debouncer-full.
Features
List of compilation features, see below for details
serdefor serialization of eventsmacos_fsevent(default) for the FSEvents backend on macOSmacos_kqueuefor the kqueue backend on macOSfreebsd_inotifyenables notify's inotify backend on FreeBSD 14.5+- inotify is automatically enabled when built natively, this feature is only needed for cross-compilation
serialization-compat-6restores the serialization behavior of notify 6, off by default
Native FreeBSD builds use inotify on 14.5+ and kqueue on older releases. When
cross-compiling for FreeBSD 14.5+, enable freebsd_inotify explicitly.
Serde
Events are serializable via serde if the serde feature is enabled:
notify = { version = "9.0.0", features = ["serde"] }
Known Problems
Network filesystems
Network mounted filesystems like NFS may not emit any events for notify to listen to.
In Linux programs running under WSL, RecommendedWatcher uses inotify.
On WSL2, changes made by Windows applications to files on Windows filesystems (such as
/mnt/c/...) may not produce inotify events, even when Watcher::watch succeeds.
See issue #254 and
microsoft/WSL#4739.
A workaround is to use PollWatcher explicitly for paths affected by these limitations.
Set the scan interval with Config::with_poll_interval (the default is 30 seconds).
Shorter intervals reduce detection latency but increase filesystem I/O.
Polling compares the state observed at each scan; changes that occur and are reverted between
scans may be missed.
Enable Config::with_compare_contents to detect changes that preserve modification times
and file sizes. This reads and hashes every regular file on each scan.
Docker with Linux on macOS M1
Docker on macOS M1 throws Function not implemented (os error 38).
You have to manually use the PollWatcher, as the native backend isn't available inside the emulation.
macOS, FSEvents and unowned files
Due to the inner security model of FSEvents (see FileSystemEventSecurity), some events cannot be observed easily when trying to follow files that do not belong to you. In this case, reverting to the pollwatcher can fix the issue, with a slight performance cost.
macOS, FSEvents: limit on watched paths
To avoid an FSEvents bug that closes unrelated file descriptors, notify limits the
combined stream roots of its FSEvents watchers to floor(soft RLIMIT_NOFILE / 12)
per process (21 for a soft limit of 256). This is a precaution based on observed
behavior, not a limit documented by Apple.
Nested watches on the same volume share a recursive ancestor's stream root. Files beneath that root do not count separately.
An operation that exceeds the current limit fails with ErrorKind::MaxFilesWatch,
leaving existing watches running. Removing a recursive watch or changing it to
RecursiveMode::NonRecursive can expose nested watches as separate roots;
unwatch those first if necessary. Lowering the soft limit can also prevent removals
until the replacement stream fits.
Watcher::update_paths checks each operation and preserves successful earlier operations.
To watch more paths, raise RLIMIT_NOFILE, watch a common ancestor recursively, or
use another backend. kqueue also has descriptor limits; PollWatcher avoids this limit.
macOS/APFS: std::fs::copy can trigger events on the source path
On APFS, std::fs::copy may use copy-on-write cloning (fclonefileat/clonefile).
This can update inode metadata on the source file, and FSEvents may report a metadata change
for the source path (see issue #259 and
issue #465).
Workarounds are to avoid std::fs::copy (use std::io::copy or read/write instead), or
filter out metadata-only events if they're not relevant (e.g. don't include
EventKindMask::MODIFY_META in Config::with_event_kinds).
Editor Behavior
If you rely on precise events (Write/Delete/Create..), you will notice that the actual events can differ a lot between file editors. Some truncate the file on save, some create a new one and replace the old one. With inotify, a watch follows the file's inode, so replacing the file can stop notifications for subsequent saves.
To observe subsequent saves after a file is replaced, watch its parent directory with
RecursiveMode::NonRecursive and filter events whose Event::paths contain the target
file's path. Check all paths in an event, since a rename event can include both the old and
new paths.
This relies on filesystem notifications; for the WSL2 limitation above, use PollWatcher.
See also issue #247 and
issue #113.
Changes to watched paths
Renaming, moving, or deleting a directly watched file or directory affects backends differently:
| Backend | Rename / move | Delete | New item at original path |
|---|---|---|---|
| inotify | Old object, old paths | Watch ends | Rewatch required |
| Windows (directory) | Old object, old paths | Watch ends | Rewatch required |
| Windows (file) | Original path | Watch kept | Events possible |
| FSEvents (macOS) | Original path | Watch kept | Events possible |
| kqueue | Watch ends | Watch ends | Rewatch required |
PollWatcher |
Original path | Watch kept | Detected on scan |
Exact events depend on the filesystem and operation; see issue #554. Windows may emit no event for a directory rename or move.
To detect changes to /a/b, also watch /a with RecursiveMode::NonRecursive and
recheck the target when the parent reports a change. Remove any surviving watch with
Watcher::unwatch before watching the desired path again, once it exists.
This assumes the parent stays in place; see issue #403.
For a fixed path that may disappear and return, use PollWatcher. The path must exist
when registered; changes that occur and are reverted between scans can be missed.
kqueue: event details
kqueue does not identify the type of a deleted entry, and this backend does not cache it,
so removal events use event::RemoveKind::Any.
A non-recursive directory watch reports changes to directory entries as events on the
directory itself, without identifying the affected child. Watch individual files to receive
their data changes, or use RecursiveMode::Recursive to track children.
See issue #644.
Recursive watches discover new entries by scanning directories after a notification. Files created and removed between scans and intermediate paths in rapid renames can be missed. Descendants found while registering a newly created directory are watched, but do not receive individual creation events. Do not rely on receiving a separate event for every operation.
kqueue: recursive watches and file descriptor limits
The kqueue backend keeps an open file descriptor for each watched file and directory.
Large recursive watches, including /, can exceed the process or system limit and fail
with ErrorKind::MaxFilesWatch. On macOS, use FSEvents for large trees: keep the default
features (or enable macos_fsevent) and do not enable macos_kqueue. Enabling macos_kqueue
also changes RecommendedWatcher to kqueue, even when macos_fsevent is enabled.
During a recursive kqueue watch, missing children are skipped. Other child errors, such as
permission failures or symbolic link cycles, are sent to the event handler while the walk
continues through the rest of the tree. A successful watch() can therefore leave some
descendants unwatched; handle error events to detect incomplete coverage.
Failure to watch or read the requested root, reaching the watch limit, or failure to register
the watches returns an error from watch(). Already installed watches are not rolled back.
Recursive kqueue watches skip FIFOs, sockets, and device files without reporting errors.
Symbolic links to these special files are also skipped. Watching a special file directly
returns an ErrorKind::Io error with std::io::ErrorKind::Unsupported.
When filesystem events trigger further watch additions, failures are sent to the event handler; reaching the watch limit stops the remaining additions in that batch. Repeated recoverable errors for the same known path are reported once per request or event batch. Later changes to the parent directory can retry failed entries and report errors again.
See issue #703, issue #455, and issue #596.
Pseudo Filesystems like /proc, /sys
Some filesystems like /proc and /sys on *nix do not emit change events or use correct file change dates.
To circumvent that problem you can use the PollWatcher with the compare_contents option.
Linux: Bad File Descriptor / No space left on device
This may be the case of running into the max-files watched limits of your user or system. (Files also includes folders.) Note that for recursive watched folders each file and folder inside counts towards the limit.
You may increase this limit in linux via
sudo sysctl fs.inotify.max_user_instances=8192 # example number
sudo sysctl fs.inotify.max_user_watches=524288 # example number
sudo sysctl -p
Note that the PollWatcher is not restricted by this limitation, so it may be an alternative if your users can't increase the limit.
Watching large directories
When watching a very large amount of files, notify may fail to receive all events. For example the linux backend is documented to not be a 100% reliable source. See also issue #412.
Watching many paths on macOS
Use Watcher::update_paths to register many paths in one batch. The FSEvents backend
rebuilds its stream when adding a path that is not already covered by a recursive watch on
the same volume. Adding N independent paths with separate Watcher::watch calls therefore
registers O(N²) paths in total; a single batch rebuilds the stream only once.
Examples
For more examples visit the examples folder in the repository.
use notify::{Event, RecursiveMode, Result, Watcher};
use std::{path::Path, sync::mpsc};
fn main() -> Result<()> {
let (tx, rx) = mpsc::channel::<Result<Event>>();
// Use recommended_watcher() to automatically select the best implementation
// for your platform. The `EventHandler` passed to this constructor can be a
// closure, a `std::sync::mpsc::Sender`, a `crossbeam_channel::Sender`, or
// another type the trait is implemented for.
let mut watcher = notify::recommended_watcher(tx)?;
// Add a path to be watched. All files and directories at that path and
// below will be monitored for changes.
# #[cfg(not(any(
# target_os = "freebsd",
# target_os = "openbsd",
# target_os = "dragonfly",
# target_os = "netbsd")))]
# { // "." doesn't exist on BSD for some reason in CI
watcher.watch(Path::new("."), RecursiveMode::Recursive)?;
# }
# #[cfg(any())]
# { // don't run this in doctests, it blocks forever
// Block forever, printing out events as they come in
for res in rx {
match res {
Ok(event) => println!("event: {:?}", event),
Err(e) => println!("watch error: {:?}", e),
}
}
# }
Ok(())
}
With different configurations
It is possible to create several watchers with different configurations or implementations that all call the same event function. This can accommodate advanced behavior or work around limits.
# use notify::{RecursiveMode, Result, Watcher};
# use std::path::Path;
#
# fn main() -> Result<()> {
fn event_fn(res: Result<notify::Event>) {
match res {
Ok(event) => println!("event: {:?}", event),
Err(e) => println!("watch error: {:?}", e),
}
}
let mut watcher1 = notify::recommended_watcher(event_fn)?;
// we will just use the same watcher kind again here
let mut watcher2 = notify::recommended_watcher(event_fn)?;
# #[cfg(not(any(
# target_os = "freebsd",
# target_os = "openbsd",
# target_os = "dragonfly",
# target_os = "netbsd")))]
# { // "." doesn't exist on BSD for some reason in CI
# watcher1.watch(Path::new("."), RecursiveMode::Recursive)?;
# watcher2.watch(Path::new("."), RecursiveMode::Recursive)?;
# }
// dropping the watcher1/2 here (no loop etc) will end the program
#
# Ok(())
# }
Modules
Structs
- Config Watcher Backend configuration
- Error Notify error type.
- Event
- EventKindMask
- INotifyWatcher Watcher implementation based on inotify
-
NullWatcher
Stub
Watcherimplementation -
PollWatcher
A
Watcherthat detects changes by periodically scanning paths. -
UpdatePathsError
The error provided by
crate::Watcher::update_pathsmethod. - WatchPathConfig Single watch backend configuration
-
WatchedPath
A registered path and its recursive mode, returned by
Watcher::watched_paths.
Enums
- ErrorKind Error kinds
- EventKind
- PathOp An operation to apply to a watcher
- RecursiveMode Indicates whether only the provided directory or its sub-directories as well should be watched
- WatcherKind Watcher kind enumeration
- WindowsPathSeparatorStyle Controls how path separators are represented in emitted event paths on Windows.
Traits
- EventHandler The set of requirements for watcher event handling functions.
- Watcher Type that can deliver file activity notifications
Functions
-
recommended_watcher
Convenience method for creating the
RecommendedWatcherfor the current platform.
Type Aliases
-
RecommendedWatcher
The recommended
Watcherimplementation for the current platform -
Result
Type alias to use this library's
Errortype in a Result