-
Notifications
You must be signed in to change notification settings - Fork 14
/
main.go
76 lines (61 loc) · 1.3 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
package main
import (
"flag"
"log"
"os"
"os/user"
"path"
)
func main() {
usr, err := user.Current()
if err != nil {
log.Fatal(err)
}
configFilePath := flag.String("c", path.Join(usr.HomeDir, ".pandik.json"), "Configuration file")
logFilePath := flag.String("l", path.Join(usr.HomeDir, ".pandik.log"), "Log file path for deamon")
deamon := flag.Bool("d", false, "Run as a deamon")
flag.Parse()
if *deamon {
args := []string{os.Args[0], "-c", *configFilePath}
pid, err := deamonize(args, *logFilePath)
if err != nil {
log.Fatal(err)
}
println(pid)
return
}
config, err := parseConfig(configFilePath)
if err != nil {
log.Fatal(err)
}
server, err := NewServer(config)
if err != nil {
log.Fatal(err)
}
server.Loop()
}
func deamonize(args []string, logFilePath string) (int, error) {
cwd, err := os.Getwd()
if err != nil {
return -1, err
}
path, err := os.Readlink("/proc/self/exe")
if err != nil {
return -1, err
}
logFile, err := os.Create(logFilePath)
if err != nil {
return -1, err
}
procattr := os.ProcAttr{Dir: cwd, Env: os.Environ(), Files: []*os.File{logFile, logFile, logFile}}
p, err := os.StartProcess(path, args, &procattr)
if err != nil {
return -1, err
}
pid := p.Pid
err = p.Release()
if err != nil {
return -1, err
}
return pid, nil
}