Vigilante de Archivos
Sin inotify/kqueue, la vigilancia de archivos usa polling: llamar a stat() periódicamente y comparar el mtime. stat devuelve [size, mode, mtime, is_dir, is_regular].
Código
// 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
}
Salida
watching: /tmp/nyx_watch_test.txt initial mtime: ... file size: 15 bytes file changed! new mtime: ... new size: 17 bytes
Explicación
stat(path) devuelve un array con cinco elementos: [size, mode, mtime, is_dir, is_regular]. El campo mtime es la última hora de modificación del archivo como timestamp Unix.
Esta receta crea un archivo, registra su mtime inicial, espera poco más de un segundo (para asegurar que el timestamp del sistema de archivos cambie), modifica el archivo y verifica el mtime de nuevo. Si el nuevo mtime es mayor, el archivo cambió.
Este enfoque de polling funciona en cualquier sistema de archivos, pero no es eficiente para vigilar muchos archivos. Para uso en producción, convendría usar bindings de inotify (Linux) o kqueue (macOS), a los que Nyx puede acceder vía FFI.