File Watcher
Without inotify/kqueue, file watching uses polling: call stat() periodically and compare the mtime. stat returns [size, mode, mtime, is_dir, is_regular].
Code
// File watcher — polling for file changes with stat()
// Vigilante de archivos — polling de cambios con stat()
fn main() -> int {
let path: String = "/tmp/nyx_watch_test.txt"
// Create a test file
write_file(path, "initial content")
print("watching: " + path)
// stat() returns [size, mode, mtime, is_dir, is_regular]
let info: Array = stat(path)
let initial_mtime: int = info[2]
print("initial mtime: " + int_to_string(initial_mtime))
print("file size: " + int_to_string(info[0]) + " bytes")
// Modify the file
sleep(1100)
write_file(path, "modified content!")
// Check again
let info2: Array = stat(path)
let new_mtime: int = info2[2]
if new_mtime > initial_mtime {
print("file changed! new mtime: " + int_to_string(new_mtime))
print("new size: " + int_to_string(info2[0]) + " bytes")
} else {
print("no change detected")
}
return 0
}
Output
watching: /tmp/nyx_watch_test.txt initial mtime: ... file size: 15 bytes file changed! new mtime: ... new size: 17 bytes
Explanation
stat(path) returns an array with five elements: [size, mode, mtime, is_dir, is_regular]. The mtime field is the file's last modification time as a Unix timestamp.
This recipe creates a file, records its initial mtime, waits just over one second (to ensure the filesystem timestamp changes), modifies the file, and checks the mtime again. If the new mtime is greater, the file has changed.
This polling approach works on any filesystem but is not efficient for watching many files. For production use, you would want inotify (Linux) or kqueue (macOS) bindings, which Nyx can access via FFI.