-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
125 lines (113 loc) · 2.34 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
114
115
116
117
118
119
120
121
122
123
124
125
package main
import (
"errors"
"os"
"log"
"syscall"
"github.com/urfave/cli"
"time"
"runtime"
"strings"
"fmt"
)
var (
logFileName = "process.log"
)
func init() {
log.SetPrefix("【main】")
}
func main() {
logFile, logErr := os.OpenFile(logFileName, os.O_CREATE|os.O_RDWR|os.O_APPEND, 0666)
defer logFile.Close()
if logErr != nil {
fmt.Println("Fail to find", *logFile, "process.log start Failed")
os.Exit(1)
}
log.SetOutput(logFile)
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)
app := cli.NewApp()
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "c",
Value: "config.yaml",
Usage: "请输入配置文件目录",
},
}
app.Action = func(c *cli.Context) error {
configFile := c.String("c")
if configFile == "" {
return errors.New("配置文件不能为空")
}
_, err := os.Open(configFile)
if err != nil && os.IsNotExist(err) {
return errors.New("配置文件不存在")
}
return nil
}
err := app.Run(os.Args)
if err != nil {
log.Fatalln("获取参数异常,信息: ", err)
}
// create daemon process
daemon(0, 1)
for {
time.Sleep(time.Second * 1)
}
}
func daemon(nochdir, noclose int) int {
var ret, ret2 uintptr
var err syscall.Errno
// platform macos linux unix
platform := []string{"darwin", "linux", "unix"}
runPlatform := runtime.GOOS
darwin := false
for _, value := range (platform) {
if strings.EqualFold(runPlatform, value) {
darwin = true
}
}
// already a daemon
if syscall.Getppid() == 1 {
return 0
}
// fork off the parent process
ret, ret2, err = syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
if err != 0 {
return -1
}
// failure
if ret2 < 0 {
os.Exit(-1)
}
// handle exception for darwin
if darwin && ret2 == 1 {
ret = 0
}
// if we got a good PID, then we call exit the parent process.
if ret > 0 {
os.Exit(0)
}
/* Change the file mode mask */
_ = syscall.Umask(0)
// create a new SID for the child process
s_ret, s_errno := syscall.Setsid()
if s_errno != nil {
log.Printf("Error: syscall.Setsid errno: %d", s_errno)
}
if s_ret < 0 {
return -1
}
if nochdir == 0 {
os.Chdir("/")
}
if noclose == 0 {
f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
if e == nil {
fd := f.Fd()
syscall.Dup2(int(fd), int(os.Stdin.Fd()))
syscall.Dup2(int(fd), int(os.Stdout.Fd()))
syscall.Dup2(int(fd), int(os.Stderr.Fd()))
}
}
return 0
}