增加 守护进程
This commit is contained in:
parent
bead88c5e2
commit
cb86b0dbe6
50
deamon.go
Normal file
50
deamon.go
Normal file
@ -0,0 +1,50 @@
|
||||
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" {
|
||||
logAndExit(PreError, "daemons mode cannot run on windows.")
|
||||
}
|
||||
err := stopDeamon()
|
||||
if err != nil {
|
||||
logAndExit(PreError, err)
|
||||
}
|
||||
_, err = exec.LookPath("fileboy")
|
||||
if err != nil {
|
||||
logAndExit(PreError, "cannot found `fileboy` command in the PATH")
|
||||
}
|
||||
deamon := exec.Command("fileboy")
|
||||
deamon.Dir = projectFolder
|
||||
deamon.Env = os.Environ()
|
||||
deamon.Stdout = os.Stdout
|
||||
err = deamon.Start()
|
||||
if err != nil {
|
||||
logAndExit(PreError, err)
|
||||
}
|
||||
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
|
||||
}
|
21
fileboy.go
21
fileboy.go
@ -238,17 +238,32 @@ func watchChangeHandler(event fsnotify.Event) {
|
||||
}
|
||||
|
||||
func parseArgs() {
|
||||
switch len(os.Args) {
|
||||
case 1:
|
||||
switch {
|
||||
case len(os.Args) == 1:
|
||||
parseConfig()
|
||||
done := make(chan bool)
|
||||
initWatcher()
|
||||
defer watcher.Close()
|
||||
<-done
|
||||
return
|
||||
case 2:
|
||||
case len(os.Args) > 1:
|
||||
c := os.Args[1]
|
||||
switch c {
|
||||
case "deamon":
|
||||
pid, err := runAsDeamon()
|
||||
if err != nil {
|
||||
logAndExit(PreError, err)
|
||||
}
|
||||
log.Println("PID:", pid)
|
||||
log.Println("fileboy is ready. the main process will run as a daemons")
|
||||
return
|
||||
case "stop":
|
||||
err := stopDeamon()
|
||||
if err != nil {
|
||||
logAndExit(PreError, err)
|
||||
}
|
||||
log.Println("fileboy daemon is stoped.")
|
||||
return
|
||||
case "init":
|
||||
_, err := ioutil.ReadFile(getFileGirlPath())
|
||||
if err == nil {
|
||||
|
Loading…
Reference in New Issue
Block a user