Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

inotify: fix race in Close() #465

Merged
merged 1 commit into from Jul 22, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 3 additions & 0 deletions inotify.go
Expand Up @@ -72,12 +72,15 @@ func (w *Watcher) isClosed() bool {

// Close removes all watches and closes the events channel.
func (w *Watcher) Close() error {
w.mu.Lock()
if w.isClosed() {
w.mu.Unlock()
return nil
}

// Send 'close' signal to goroutine, and set the Watcher to closed.
close(w.done)
w.mu.Unlock()

// Wake up goroutine
w.poller.wake()
Expand Down
18 changes: 10 additions & 8 deletions inotify_test.go
Expand Up @@ -354,14 +354,16 @@ func TestInotifyInnerMapLength(t *testing.T) {
_ = <-w.Events // consume Remove event
<-time.After(50 * time.Millisecond) // wait IN_IGNORE propagated

w.mu.Lock()
defer w.mu.Unlock()
if len(w.watches) != 0 {
t.Fatalf("Expected watches len is 0, but got: %d, %v", len(w.watches), w.watches)
}
if len(w.paths) != 0 {
t.Fatalf("Expected paths len is 0, but got: %d, %v", len(w.paths), w.paths)
}
func() {
w.mu.Lock()
defer w.mu.Unlock()
if len(w.watches) != 0 {
t.Fatalf("Expected watches len is 0, but got: %d, %v", len(w.watches), w.watches)
}
if len(w.paths) != 0 {
t.Fatalf("Expected paths len is 0, but got: %d, %v", len(w.paths), w.paths)
}
}()

w.Close()
wg.Wait()
Expand Down
15 changes: 15 additions & 0 deletions integration_test.go
Expand Up @@ -1244,6 +1244,21 @@ func TestRemoveWithClose(t *testing.T) {
}
}

// Make sure Close() doesn't race; hard to write a good reproducible test for
// this, but running it 150 times seems to reproduce it in ~75% of cases and
// isn't too slow (~0.06s on my system).
func TestCloseRace(t *testing.T) {
for i := 0; i < 150; i++ {
w, err := NewWatcher()
if err != nil {
t.Fatal(err)
}
go w.Close()
go w.Close()
go w.Close()
}
}

func testRename(file1, file2 string) error {
switch runtime.GOOS {
case "windows", "plan9":
Expand Down