Skip to content

Instantly share code, notes, and snippets.

@Garlandal
Last active March 7, 2019 04:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Garlandal/da31d0d660f643e829a7577700ca4cca to your computer and use it in GitHub Desktop.
Save Garlandal/da31d0d660f643e829a7577700ca4cca to your computer and use it in GitHub Desktop.
package main
import (
"bufio"
"fmt"
"github.com/fsnotify/fsnotify"
"io"
"log"
"os"
"path"
"time"
)
func addaWatch(fileName string, watcher *fsnotify.Watcher) error {
for {
err := watcher.Add(fileName)
if err != nil {
log.Println(err)
time.Sleep(1 * time.Second)
} else {
return nil
}
}
}
func openFile(fileName string) *os.File {
for {
file, err := os.Open(fileName)
if err != nil {
log.Println(err)
time.Sleep(1 * time.Second)
} else {
return file
}
}
}
func readFile(quit chan bool, fileName string) {
println("reading file...........", fileName)
file := openFile(fileName)
defer file.Close()
reader := bufio.NewReader(file)
for {
select {
case canQuit := <-quit:
if canQuit {
println("quit goroutine")
return
}
default:
line, err := reader.ReadString('\n')
if err != nil {
if err == io.EOF {
time.Sleep(1 * time.Second)
} else {
break
}
}
fmt.Print(string(line))
//fmt.Println("num of goroutine", runtime.NumGoroutine())
}
}
}
func main() {
absPath := "/Users/garland/code/go/src/yat/tt"
basePath, targetFile := path.Split(absPath)
println(basePath, targetFile)
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
done := make(chan bool)
quit := make(chan bool)
go readFile(quit, absPath)
go func() {
for {
select {
case event := <-watcher.Events:
if event.Op&fsnotify.Create == fsnotify.Create {
log.Println("create file:", event.Name, event.Op)
if event.Name == absPath {
//println("------newfile created----------------")
quit <- true
time.Sleep(2 * time.Second)
go readFile(quit, absPath)
}
}
case err := <-watcher.Errors:
log.Println("error:", err)
}
}
}()
addaWatch(basePath, watcher)
<-done
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment