增加 守护进程

This commit is contained in:
dengsgo 2019-12-23 16:13:31 +08:00
parent bead88c5e2
commit cb86b0dbe6
3 changed files with 72 additions and 3 deletions

50
deamon.go Normal file
View 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
}

View File

@ -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 {

4
raw.go
View File

@ -96,6 +96,10 @@ Usage of fileboy:
初始化 fileboy, 在当前目录生成 filegirl.yaml 配置文件
exec
尝试运行定义的 command 命令
deamon
读取当前目录下的 filegirl.yaml 配置以守护进程的方式运行在后台
stop
停止守护进程
version
查看当前版本信息
`