1
0
mirror of https://github.com/Mrs4s/go-cqhttp.git synced 2025-05-04 19:17:37 +08:00
go-cqhttp/server/daemon.go
wdvxdr ee73fca2ce
ci: update golangci-lint
fix golint
update golangci-lint
2021-03-16 13:33:55 +08:00

74 lines
1.6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// daemon 功能写在这,目前仅支持了-d 作为后台运行参数stopstartrestart这些功能目前看起来并不需要可以通过api控制后续需要的话再补全。
package server
import (
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"
"github.com/Mrs4s/go-cqhttp/global"
log "github.com/sirupsen/logrus"
)
// Daemon go-cqhttp server 的 daemon的实现函数
func Daemon() {
args := os.Args[1:]
execArgs := make([]string, 0)
l := len(args)
for i := 0; i < l; i++ {
if strings.Index(args[i], "-d") == 0 {
continue
}
execArgs = append(execArgs, args[i])
}
proc := exec.Command(os.Args[0], execArgs...)
err := proc.Start()
if err != nil {
panic(err)
}
log.Info("[PID] ", proc.Process.Pid)
// pid写入到pid文件中方便后续stop的时候kill
pidErr := savePid("go-cqhttp.pid", fmt.Sprintf("%d", proc.Process.Pid))
if pidErr != nil {
log.Errorf("save pid file error: %v", pidErr)
}
os.Exit(0)
}
// savePid 保存pid到文件中便于后续restart/stop的时候kill pid用。
func savePid(path string, data string) error {
return global.WriteAllText(path, data)
}
// GetCurrentPath 预留,获取当前目录地址
func GetCurrentPath() (string, error) {
file, err := exec.LookPath(os.Args[0])
if err != nil {
return "", err
}
path, err := filepath.Abs(file)
if err != nil {
return "", err
}
if runtime.GOOS == "windows" {
path = strings.ReplaceAll(path, "\\", "/")
}
i := strings.LastIndex(path, "/")
if i < 0 {
return "", errors.New("system/path_error,Can't find '/' or '\\'")
}
return path[0 : i+1], nil
}