Detecting file changes on macOS with kqueue
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.
... continue reading