Go library shows filesystem changes across platforms
Programming Snapshot – fsnotify
Inotify lets applications subscribe to change notifications in the filesystem. Mike Schilli uses the cross-platform fsnotify library to instruct a Go program to detect what's happening.
In a file manager, have you ever observed how newly created files by other applications immediately appear in the displayed directory and wondered how this works? As continuous querying of the filesystem is out of the question for performance reasons, these applications use the Linux filesystem's inotify interface instead.
Operating systems implement the mechanism in different ways: Linux uses inotify, the Mac uses kqueue, and Windows comes with an unpronounceable extra. Fortunately, the Go library fsnotify on GitHub abstracts this proliferation to create a simple interface. This means that programmers only need to write their applications once to cover all platforms.
No Stress
About 15 years ago, I wrote an article on this topic in my regular column [1]. At the time I used Perl, and the article relied on FUSE, a special filesystem. Today filesystem notifications are part of the standard.
In Go, the whole thing can be done without much fuss; Listing 1 shows a simple example just to get you warmed up. Figure 1 visualizes how an executable binary named watch
is created from the Go code in watch.go
, which then starts monitoring a newly created directory /tmp/test/
. In another terminal, the user now enters the commands shown in Figure 2. They first create a new file in the test directory, write data to it, change its execution privileges, and finally delete it with rm
. Figure 1 confirms that the Go program actually sees all changes in real time and logs the actions.
Listing 1
watch.go
01 package main 02 03 import ( 04 "fmt" 05 "github.com/fsnotify/fsnotify" 06 ) 07 08 func main() { 09 watcher, err := fsnotify.NewWatcher() 10 if err != nil { 11 panic(err) 12 } 13 defer watcher.Close() 14 15 go func() { 16 for { 17 select { 18 case event, ok := <-watcher.Events: 19 if !ok { 20 return 21 } 22 fmt.Printf("%+v\n", event) 23 } 24 } 25 }() 26 27 err = watcher.Add("/tmp/test") 28 if err != nil { 29 panic(err) 30 } 31 32 done := make(chan struct{}) 33 <-done 34 }
To do this, Listing 1 retrieves the library code from GitHub in line 5, creates a new watcher as the first step in the main
program, and calls defer
to tell it to shut itself down at the end of the program.
Since filesystem monitoring with fsnotify is an asynchronous process using Go channels, line 15 calls go func
to launch a goroutine, which immediately starts an infinite loop with a select
statement. The latter blocks the flow of the goroutine until messages arrive from the watcher.Events
channel, sent by the library code from fsnotify, which gets its clues directly from the operating system.
Routines and Blocking
Meanwhile, the main
program continues to flow unimpeded, and line 27 tells fsnotify via watcher.Add()
that it wants to monitor the /tmp/test/
directory. That's all there is to it in the main
program.
But since main
is supposed to continue running and listening for events in the Goroutine launched earlier; line 32 creates an unused channel just before the end in line 33. Alas, no message will ever arrive from this channel: Its only job is to block the main
program until the user cancels it by pressing Ctrl+C.
Non-Recursive
The Go library fsnotify only adds one directory to the watch list with each call to Add()
. Recursive integration of an entire file tree is supposedly on the fsnotify project's roadmap, but it doesn't work at the moment. Therefore, the application has to weave its own surveillance net by issuing recursive calls down the directory hierarchy.
For example, to track which files the Go compiler downloads or generates in the directory hierarchy below ~/go/
in the user's home directory during the work phase, Listing 2 first has to delve the depths of the directory structure using the Walk()
function from the standard filepath
package starting in line 24.
Listing 2
fswatch.go
01 package main 02 03 import ( 04 "fmt" 05 "github.com/fsnotify/fsnotify" 06 "log" 07 "os" 08 "os/user" 09 "path/filepath" 10 "strings" 11 ) 12 13 func main() { 14 cur, err := user.Current() 15 dieOnErr(err) 16 home := cur.HomeDir 17 18 watcher, err := fsnotify.NewWatcher() 19 dieOnErr(err) 20 defer watcher.Close() 21 22 watchInit(watcher) 23 24 err = filepath.Walk(filepath.Join(home, "go"), 25 func(path string, info os.FileInfo, err error) error { 26 dieOnErr(err) 27 if info.IsDir() { 28 err := watcher.Add(path) 29 dieOnErr(err) 30 } 31 return nil 32 }) 33 dieOnErr(err) 34 35 done := make(chan bool) 36 <-done 37 } 38 39 func eventAsString(event fsnotify.Event) string { 40 info, err := os.Stat(event.Name) 41 dieOnErr(err) 42 evShort := (strings.ToLower(event.Op.String()))[0:2] 43 dirParts := strings.Split(event.Name, "/") 44 pathShort := event.Name 45 if len(dirParts) > 3 { 46 pathShort = filepath.Join(dirParts[len(dirParts)-3 : len(dirParts)]...) 47 } 48 return fmt.Sprintf("%s %s %d", evShort, pathShort, info.Size()) 49 } 50 51 func watchInit(watcher *fsnotify.Watcher) { 52 go func() { 53 for { 54 select { 55 case event, ok := <-watcher.Events: 56 if !ok { 57 return 58 } 59 if event.Op&fsnotify.Rename == fsnotify.Rename || 60 event.Op&fsnotify.Remove == fsnotify.Remove { 61 continue 62 } 63 log.Printf("%s\n", eventAsString(event)) 64 info, err := os.Stat(event.Name) 65 dieOnErr(err) 66 if info.IsDir() { 67 err := watcher.Add(event.Name) 68 dieOnErr(err) 69 } 70 case err, _ := <-watcher.Errors: 71 panic(err) 72 } 73 } 74 }() 75 } 76 77 func dieOnErr(err error) { 78 if err != nil { 79 panic(err) 80 } 81 }
As a parameter, the function expects a callback function that it will call for each filesystem entry it finds with the name and the FileInfo
structure including the metadata, such as the file or directory, size in bytes, or access permissions. If an error occurred during the traversal, the err
variable is set to the corresponding error instead.
Buy this article as PDF
(incl. VAT)
Buy Linux Magazine
Subscribe to our Linux Newsletters
Find Linux and Open Source Jobs
Subscribe to our ADMIN Newsletters
Support Our Work
Linux Magazine content is made possible with support from readers like you. Please consider contributing when you’ve found an article to be beneficial.
News
-
Gnome 48 Debuts New Audio Player
To date, the audio player found within the Gnome desktop has been meh at best, but with the upcoming release that all changes.
-
Plasma 6.3 Ready for Public Beta Testing
Plasma 6.3 will ship with KDE Gear 24.12.1 and KDE Frameworks 6.10, along with some new and exciting features.
-
Budgie 10.10 Scheduled for Q1 2025 with a Surprising Desktop Update
If Budgie is your desktop environment of choice, 2025 is going to be a great year for you.
-
Firefox 134 Offers Improvements for Linux Version
Fans of Linux and Firefox rejoice, as there's a new version available that includes some handy updates.
-
Serpent OS Arrives with a New Alpha Release
After months of silence, Ikey Doherty has released a new alpha for his Serpent OS.
-
HashiCorp Cofounder Unveils Ghostty, a Linux Terminal App
Ghostty is a new Linux terminal app that's fast, feature-rich, and offers a platform-native GUI while remaining cross-platform.
-
Fedora Asahi Remix 41 Available for Apple Silicon
If you have an Apple Silicon Mac and you're hoping to install Fedora, you're in luck because the latest release supports the M1 and M2 chips.
-
Systemd Fixes Bug While Facing New Challenger in GNU Shepherd
The systemd developers have fixed a really nasty bug amid the release of the new GNU Shepherd init system.
-
AlmaLinux 10.0 Beta Released
The AlmaLinux OS Foundation has announced the availability of AlmaLinux 10.0 Beta ("Purple Lion") for all supported devices with significant changes.
-
Gnome 47.2 Now Available
Gnome 47.2 is now available for general use but don't expect much in the way of newness, as this is all about improvements and bug fixes.