Detecting file changes on macOS with kqueue

https://news.ycombinator.com/rss Hits: 14
Summary

Detecting file changes on macOS with kqueue 2026-03-24 A while ago I wrote a small file watcher in Go for my own use with an accompanying blog post. I needed a tool that I could just plop in front of the command I was running as part of my iteration loop. I use it for recompiling C files when I modify them, reload gcc main.c -o main && ./main and for rebuilding and reloading my static site on file changes. reload make It has two modes. If one or more explicit files are mentioned in the command, it will watch those files. If it does not find any filenames, it will watch all files in the working directory. The only thing reload needs to know is whether any file it is watching has changed. If a file has changed, it reruns the command. It works great! But I copped out on the part that was the most unfamiliar to me, namely detecting file changes. I used the fsnotify package which is a nice cross-platform Go library for this. It supports macOS as well as Linux but since it's for my own use, I don't care about Linux support. More importantly, I wanted to understand what fsnotify did under the hood. On macOS it uses the kqueue event notification interface. Let's take a look at how this works, writing some C code to test it, and then finally implement it in the reload Go program. #kqueue data structures The kqueue() function call creates a new kernel event queue (a kqueue) and returns a file descriptor. We register and wait for system events using the kevent() function call, which uses the kevent data structure. This has five fields that we need to care about. ident The source of the event. In this case, it will be a file descriptor for the file we want to watch. filter The kernel filter used to process the event. flags Actions to perform on the event. fflags Filter-specific flags. udata Opaque user data identifier. We'll use this to store the filename for easy lookup later. Well, which kernel filter do we use if we want to watch a file for changes? There are 9 possible filt...

First seen: 2026-03-28 18:43

Last seen: 2026-03-29 08:50