-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
98 lines (85 loc) · 1.81 KB
/
main.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"flag"
"io/ioutil"
"log"
"os"
"strconv"
"strings"
"syscall"
"github.com/fsnotify/fsnotify"
)
var (
fileToWatch *string
pidFile *string
)
func init() {
fileToWatch = flag.String("fileToWatch", "config.conf", "the file to watch for changes")
pidFile = flag.String("pidFile", "pidfile.pid", "the file containing the PID of the process to receive the SIGHUP")
}
func main() {
flag.Parse()
watcher, err := fsnotify.NewWatcher()
if err != nil {
log.Fatal(err)
}
defer watcher.Close()
done := make(chan bool)
go func() {
for {
select {
case event, ok := <-watcher.Events:
if !ok {
return
}
if event.Op&fsnotify.Remove == fsnotify.Remove ||
event.Op&fsnotify.Rename == fsnotify.Rename {
// if the file was removed or renamed, linux inotify
// removes the watch, so re-add it
err = watcher.Add(*fileToWatch)
if err != nil {
log.Fatal(err)
}
}
if event.Op&fsnotify.Write == fsnotify.Write {
log.Printf("change detected (%s)\n", event.Name)
err := sendHup()
if err != nil {
log.Printf("failed to send SIGHUP: %v\n", err)
}
}
case err, ok := <-watcher.Errors:
if !ok {
return
}
log.Println("error:", err)
}
}
}()
err = watcher.Add(*fileToWatch)
if err != nil {
log.Fatalf("%s: %v\n", *fileToWatch, err)
}
log.Printf("watching (%s)\n", *fileToWatch)
<-done
}
func sendHup() error {
content, err := ioutil.ReadFile(*pidFile)
if err != nil {
return err
}
pid, err := strconv.Atoi(strings.TrimSuffix(string(content), "\n"))
if err != nil {
return err
}
process, err := os.FindProcess(pid)
if err != nil {
return err
}
err = process.Signal(syscall.SIGHUP)
if err != nil {
return err
}
log.Printf("sent SIGHUP to %d (%s)\n", pid, *pidFile)
return nil
}