fileboy/deamon.go

51 lines
934 B
Go
Raw Permalink 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"
}
func runAsDeamon() (int, error) {
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
}
err := stopDeamon()
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
}
deamon := exec.Command("fileboy")
deamon.Dir = projectFolder
deamon.Env = os.Environ()
deamon.Stdout = os.Stdout
err = deamon.Start()
if err != nil {
2020-01-02 09:25:02 +00:00
logAndExit(err)
2019-12-23 08:13:31 +00:00
}
pid := deamon.Process.Pid
if pid != 0 {
ioutil.WriteFile(getPidFile(), []byte(strconv.Itoa(pid)), 0644)
}
return pid, nil
}
func stopDeamon() error {
bs, err := ioutil.ReadFile(getPidFile())
if err != nil {
return nil
}
_ = exec.Command("kill", string(bs)).Run()
os.Remove(getPidFile())
return nil
}