Go library shows filesystem changes across platforms
Programming Snapshot – fsnotify
![© Lead Image © alphaspirit, 123RF.com © Lead Image © alphaspirit, 123RF.com](/var/linux_magazin/storage/images/issues/2021/247/motion-sensor/123rf-alphaspirit_running_man_laptop.png/785894-1-eng-US/123RF-alphaspirit_running_man_laptop.png_medium.png)
© Lead Image © alphaspirit, 123RF.com
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.
![Learn More](https://www.linux-magazine.com/var/linux_magazin/storage/images/media/linux-magazine-eng-us/images/misc/learn-more/834592-1-eng-US/Learn-More_medium.png)
News
-
NVIDIA Released Driver for Upcoming NVIDIA 560 GPU for Linux
Not only has NVIDIA released the driver for its upcoming CPU series, it's the first release that defaults to using open-source GPU kernel modules.
-
OpenMandriva Lx 24.07 Released
If you’re into rolling release Linux distributions, OpenMandriva ROME has a new snapshot with a new kernel.
-
Kernel 6.10 Available for General Usage
Linus Torvalds has released the 6.10 kernel and it includes significant performance increases for Intel Core hybrid systems and more.
-
TUXEDO Computers Releases InfinityBook Pro 14 Gen9 Laptop
Sporting either AMD or Intel CPUs, the TUXEDO InfinityBook Pro 14 is an extremely compact, lightweight, sturdy powerhouse.
-
Google Extends Support for Linux Kernels Used for Android
Because the LTS Linux kernel releases are so important to Android, Google has decided to extend the support period beyond that offered by the kernel development team.
-
Linux Mint 22 Stable Delayed
If you're anxious about getting your hands on the stable release of Linux Mint 22, it looks as if you're going to have to wait a bit longer.
-
Nitrux 3.5.1 Available for Install
The latest version of the immutable, systemd-free distribution includes an updated kernel and NVIDIA driver.
-
Debian 12.6 Released with Plenty of Bug Fixes and Updates
The sixth update to Debian "Bookworm" is all about security mitigations and making adjustments for some "serious problems."
-
Canonical Offers 12-Year LTS for Open Source Docker Images
Canonical is expanding its LTS offering to reach beyond the DEB packages with a new distro-less Docker image.
-
Plasma Desktop 6.1 Released with Several Enhancements
If you're a fan of Plasma Desktop, you should be excited about this new point release.