Skip to content

Commit 505fc25

Browse files
authored
fix: fsnotify watcher panics when closing (#3399)
1 parent 83ba887 commit 505fc25

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

os/gfsnotify/gfsnotify_watcher.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,11 +106,11 @@ func (w *Watcher) addWithCallbackFunc(name, path string, callbackFunc func(event
106106

107107
// Close closes the watcher.
108108
func (w *Watcher) Close() {
109-
w.events.Close()
109+
close(w.closeChan)
110110
if err := w.watcher.Close(); err != nil {
111111
intlog.Errorf(context.TODO(), `%+v`, err)
112112
}
113-
close(w.closeChan)
113+
w.events.Close()
114114
}
115115

116116
// Remove removes monitor and all callbacks associated with the `path` recursively.

os/gfsnotify/gfsnotify_watcher_loop.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ package gfsnotify
88

99
import (
1010
"context"
11+
1112
"github.com/gogf/gf/v2/errors/gcode"
1213
"github.com/gogf/gf/v2/errors/gerror"
1314

@@ -25,7 +26,10 @@ func (w *Watcher) watchLoop() {
2526
return
2627

2728
// Event listening.
28-
case ev := <-w.watcher.Events:
29+
case ev, ok := <-w.watcher.Events:
30+
if !ok {
31+
return
32+
}
2933
// Filter the repeated event in custom duration.
3034
_, err := w.cache.SetIfNotExist(
3135
context.Background(),

os/gfsnotify/gfsnotify_z_unit_test.go

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -218,3 +218,23 @@ func TestWatcher_WatchFolderWithoutRecursively(t *testing.T) {
218218
t.Assert(array.Len(), 1)
219219
})
220220
}
221+
222+
func TestWatcher_WatchClose(t *testing.T) {
223+
gtest.C(t, func(t *gtest.T) {
224+
var (
225+
err error
226+
dirPath = gfile.Temp(gtime.TimestampNanoStr())
227+
watcher *gfsnotify.Watcher
228+
)
229+
230+
err = gfile.Mkdir(dirPath)
231+
t.AssertNil(err)
232+
233+
watcher, err = gfsnotify.New()
234+
t.AssertNil(err)
235+
t.AssertNE(watcher, nil)
236+
237+
time.Sleep(time.Millisecond * 100)
238+
watcher.Close()
239+
})
240+
}

0 commit comments

Comments
 (0)