This commit is contained in:
gotoeasy 2022-09-14 10:10:22 +08:00
parent 46a9e7bee2
commit da22db315b
2 changed files with 85 additions and 1 deletions

View File

@ -3,6 +3,7 @@ package onstart
import (
"flag"
"fmt"
"log"
"os"
"os/exec"
"runtime"
@ -10,10 +11,26 @@ import (
func init() {
// 仅支持linux
if runtime.GOOS != "linux" {
return
}
// pid
pidfile := NewPid("~/.gologcenter/glc.pid")
if pidfile.Err != nil {
os.Exit(1) // 创建或保存pid文件失败
}
if !pidfile.IsNew {
log.Println(pidfile.Pid)
os.Exit(0) // 进程已存在,不重复启动
}
// 操作系统是linux时支持以命令行参数【-d】后台方式启动
daemon := false
for index, arg := range os.Args {
if runtime.GOOS == "linux" && index > 0 && arg == "-d" {
if index > 0 && arg == "-d" {
daemon = true
break
}

67
glc/onstart/pid.go Normal file
View File

@ -0,0 +1,67 @@
package onstart
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
)
type PidFile struct {
Path string // pid文件路径
Pid string // pid
IsNew bool // 是否新
Err error // error
}
// 指定路径下生成pid文件文件内容为pid已存在时检查pid有效性
func NewPid(pathfile string) *PidFile {
// 运行中时直接返回
if opid := checkPidFile(pathfile); opid != nil {
return opid
}
// 创建文件
if err := os.MkdirAll(filepath.Dir(pathfile), os.FileMode(0755)); err != nil {
log.Println("create pid file failed", pathfile)
return &PidFile{
Path: pathfile,
Err: err,
}
}
// 保存PID
pid := fmt.Sprintf("%d", os.Getpid())
if err := os.WriteFile(pathfile, []byte(pid), 0644); err != nil {
log.Println("save pid file failed", pathfile)
return &PidFile{
Path: pathfile,
Err: err,
}
}
// 成功创建后返回
return &PidFile{
Path: pathfile,
Pid: pid,
IsNew: false,
Err: nil,
}
}
func checkPidFile(path string) *PidFile {
if pidByte, err := os.ReadFile(path); err == nil {
pid := strings.TrimSpace(string(pidByte))
if _, err := os.Stat(filepath.Join("/proc", pid)); err == nil {
return &PidFile{
Path: path,
Pid: pid,
IsNew: false,
}
}
}
return nil
}