-
Notifications
You must be signed in to change notification settings - Fork 19
/
watchFile.go
63 lines (57 loc) · 1.38 KB
/
watchFile.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package fsutil
import (
"io"
"os"
"syscall"
"time"
"github.com/Symantec/Dominator/lib/log"
)
var stopped bool
func watchFile(pathname string, logger log.Logger) <-chan io.ReadCloser {
channel := make(chan io.ReadCloser, 1)
if !watchFileWithFsNotify(pathname, channel, logger) {
go watchFileForever(pathname, channel, logger)
}
return channel
}
func watchFileStop() {
if !watchFileStopWithFsNotify() {
stopped = true
}
}
func watchFileForever(pathname string, channel chan<- io.ReadCloser,
logger log.Logger) {
var lastStat syscall.Stat_t
lastFd := -1
for ; !stopped; time.Sleep(time.Second) {
var stat syscall.Stat_t
if err := syscall.Stat(pathname, &stat); err != nil {
if logger != nil {
logger.Printf("Error stating file: %s: %s\n", pathname, err)
}
continue
}
if stat.Ino != lastStat.Ino {
if file, err := os.Open(pathname); err != nil {
if logger != nil {
logger.Printf("Error opening file: %s: %s\n", pathname, err)
}
continue
} else {
// By holding onto the file, we guarantee that the inode number
// for the file we've opened cannot be reused until we've seen
// a new inode.
if lastFd >= 0 {
syscall.Close(lastFd)
}
lastFd, _ = syscall.Dup(int(file.Fd()))
channel <- file // Must happen after FD is duplicated.
lastStat = stat
}
}
}
if lastFd >= 0 {
syscall.Close(lastFd)
}
close(channel)
}