-
Notifications
You must be signed in to change notification settings - Fork 247
/
main.go
113 lines (96 loc) · 1.92 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"flag"
"github.com/sevlyar/go-daemon"
"log"
"os"
"syscall"
"time"
)
var (
signal = flag.String("s", "", `Send signal to the daemon:
stop — shutdown`)
)
const logFileName = "sample.log"
const pidFileName = "sample.pid"
func main() {
flag.Parse()
daemon.AddCommand(daemon.StringFlag(signal, "stop"), syscall.SIGTERM, termHandler)
cntxt := &daemon.Context{
PidFileName: pidFileName,
PidFilePerm: 0644,
LogFileName: logFileName,
LogFilePerm: 0640,
WorkDir: "./",
Umask: 027,
Args: []string{"[go-daemon sample]"},
}
if len(daemon.ActiveFlags()) > 0 {
d, err := cntxt.Search()
if err != nil {
log.Fatalf("Unable send signal to the daemon: %s", err.Error())
}
daemon.SendCommands(d)
return
}
d, err := cntxt.Reborn()
if err != nil {
log.Fatalln(err)
}
if d != nil {
return
}
defer cntxt.Release()
log.Println("- - - - - - - - - - - - - - -")
log.Println("daemon started")
setupLog()
go worker()
err = daemon.ServeSignals()
if err != nil {
log.Printf("Error: %s", err.Error())
}
log.Println("daemon terminated")
}
func setupLog() {
lf, err := NewLogFile(logFileName, os.Stderr)
if err != nil {
log.Fatalf("Unable to create log file: %s", err.Error())
}
log.SetOutput(lf)
// rotate log every 30 seconds.
rotateLogSignal := time.Tick(30 * time.Second)
go func() {
for {
<-rotateLogSignal
if err := lf.Rotate(); err != nil {
log.Fatalf("Unable to rotate log: %s", err.Error())
}
}
}()
}
var (
stop = make(chan struct{})
done = make(chan struct{})
)
func worker() {
LOOP:
for {
// spam to log every one second (as payload).
log.Print("+ ", time.Now().Unix())
time.Sleep(time.Second)
select {
case <-stop:
break LOOP
default:
}
}
done <- struct{}{}
}
func termHandler(sig os.Signal) error {
log.Println("terminating...")
stop <- struct{}{}
if sig == syscall.SIGQUIT {
<-done
}
return daemon.ErrStop
}