fileboy/daemon.go

57 lines
1.0 KiB
Go
Raw Normal View History

2019-12-23 08:13:31 +00:00
package main
import (
"io/ioutil"
"os"
"os/exec"
"runtime"
"strconv"
)
func getPidFile() string {
return projectFolder + "/.fileboy.pid"
}
2020-03-16 03:16:14 +00:00
func runAsDaemon() (int, error) {
2019-12-23 08:13:31 +00:00
if runtime.GOOS == "windows" {
2020-01-02 09:25:02 +00:00
logAndExit("daemons mode cannot run on windows.")
2019-12-23 08:13:31 +00:00
}
2020-03-16 03:16:14 +00:00
err := stopDaemon()
2019-12-23 08:13:31 +00:00
if err != nil {
2020-01-02 09:25:02 +00:00
logAndExit(err)
2019-12-23 08:13:31 +00:00
}
_, err = exec.LookPath("fileboy")
if err != nil {
2020-01-02 09:25:02 +00:00
logAndExit("cannot found `fileboy` command in the PATH")
2019-12-23 08:13:31 +00:00
}
2020-03-16 03:16:14 +00:00
daemon := exec.Command("fileboy")
daemon.Dir = projectFolder
daemon.Env = os.Environ()
daemon.Stdout = os.Stdout
err = daemon.Start()
2019-12-23 08:13:31 +00:00
if err != nil {
2020-01-02 09:25:02 +00:00
logAndExit(err)
2019-12-23 08:13:31 +00:00
}
2020-03-16 03:16:14 +00:00
pid := daemon.Process.Pid
2019-12-23 08:13:31 +00:00
if pid != 0 {
ioutil.WriteFile(getPidFile(), []byte(strconv.Itoa(pid)), 0644)
}
return pid, nil
}
2020-03-16 03:16:14 +00:00
func stopDaemon() error {
2019-12-23 08:13:31 +00:00
bs, err := ioutil.ReadFile(getPidFile())
if err != nil {
return nil
}
_ = exec.Command("kill", string(bs)).Run()
os.Remove(getPidFile())
return nil
}
2020-06-27 07:11:55 +00:00
func stopSelf() {
pid := os.Getpid()
os.Remove(getPidFile())
_ = exec.Command("kill", strconv.Itoa(pid)).Run()
}