-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathdaemon.go
59 lines (53 loc) · 1.24 KB
/
daemon.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
// Copyright (c) 2018-2022 Author dengsgo<[email protected]> [https://github.com/dengsgo/fileboy]
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
package main
import (
"os"
"os/exec"
"runtime"
"strconv"
)
func getPidFile() string {
return projectFolder + "/.fileboy.pid"
}
func runAsDaemon() (int, error) {
if runtime.GOOS == "windows" {
logAndExit("daemons mode cannot run on windows.")
}
err := stopDaemon()
if err != nil {
logAndExit(err)
}
_, err = exec.LookPath("fileboy")
if err != nil {
logAndExit("cannot found `fileboy` command in the PATH")
}
daemon := exec.Command("fileboy")
daemon.Dir = projectFolder
daemon.Env = os.Environ()
daemon.Stdout = os.Stdout
err = daemon.Start()
if err != nil {
logAndExit(err)
}
pid := daemon.Process.Pid
if pid != 0 {
os.WriteFile(getPidFile(), []byte(strconv.Itoa(pid)), 0644)
}
return pid, nil
}
func stopDaemon() error {
bs, err := os.ReadFile(getPidFile())
if err != nil {
return nil
}
_ = exec.Command("kill", string(bs)).Run()
os.Remove(getPidFile())
return nil
}
func stopSelf() {
pid := os.Getpid()
os.Remove(getPidFile())
_ = exec.Command("kill", strconv.Itoa(pid)).Run()
}