-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (71 loc) · 1.54 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
// daemonize a passed binary
package main
import (
"flag"
"fmt"
"os"
"os/exec"
"runtime"
"syscall"
)
func usage() {
fmt.Fprintf(os.Stderr, "Usage: %v [ARGS] COMMAND\n", os.Args[0])
flag.PrintDefaults()
}
func parseCmdLine(rawArgs []string, cmd *string, args *[]string) {
if len(rawArgs) == 0 {
// print usage
fmt.Fprintf(os.Stderr, "error: not enough arguments\n")
flag.Usage()
os.Exit(1)
}
*cmd = rawArgs[0]
*args = rawArgs
}
var (
clearEnv bool
cmd string
args []string
)
func init() {
flag.BoolVar(&clearEnv, "x", false, "execute the daemon with an empty environment")
flag.Usage = usage
flag.Parse()
parseCmdLine(flag.Args(), &cmd, &args)
}
func main() {
// Ensure the binary specified can be found on the current PATH
qualified, err := exec.LookPath(cmd)
if err != nil {
fmt.Fprintf(os.Stderr, "damonize: %v not found on PATH\n", cmd)
os.Exit(1)
}
// Copied from exec_bsd.go in runtime package
darwin := runtime.GOOS == "darwin"
pid, ischild, _ := syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
if darwin && ischild == 1 {
pid = 0
}
if pid > 0 {
// parent, dies
os.Exit(0)
} else {
// child, create new session and fork subprocess
syscall.Setsid()
pid, ischild, _ = syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
if darwin && ischild == 1 {
pid = 0
}
if pid > 0 {
// kill the parent
os.Exit(0)
} else {
// Execute the daemon in the new session
if clearEnv {
syscall.Exec(qualified, args, []string{})
} else {
syscall.Exec(qualified, args, os.Environ())
}
}
}
}