From 2ddc54f5ac85871a974758e54c934c839ee10ad9 Mon Sep 17 00:00:00 2001 From: boyce Date: Tue, 5 Mar 2024 17:38:02 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96node=E5=90=AF=E5=8A=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- node/node.go | 18 ++++++++++++++---- util/sysprocess/process.go | 25 +++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 4 deletions(-) create mode 100644 util/sysprocess/process.go diff --git a/node/node.go b/node/node.go index 71ee93e..1a30448 100644 --- a/node/node.go +++ b/node/node.go @@ -19,7 +19,7 @@ import ( "strings" "syscall" "time" - "github.com/shirou/gopsutil/process" + "github.com/duanhf2012/origin/util/sysprocess" ) var sig chan os.Signal @@ -293,9 +293,19 @@ func startNode(args interface{}) error { if err != nil { return err } - ok,_ := process.PidExists(int32(processId)) - if ok == true { - return fmt.Errorf("repeat runs are not allowed,node is %d,processid is %d",nodeId,processId) + + name, cErr := sysprocess.GetProcessNameByPID(int32(processId)) + myName, mErr := sysprocess.GetMyProcessName() + //当前进程名获取失败,不应该发生 + if mErr != nil { + log.SInfo("get my process's name is error,", err.Error()) + os.Exit(-1) + } + + //进程id存在,而且进程名也相同,被认为是当前进程重复运行 + if cErr == nil && name == myName { + log.SInfo(fmt.Sprintf("repeat runs are not allowed,node is %d,processid is %d",nodeId,processId)) + os.Exit(-1) } timer.StartTimer(10*time.Millisecond, 1000000) diff --git a/util/sysprocess/process.go b/util/sysprocess/process.go new file mode 100644 index 0000000..6d16d1e --- /dev/null +++ b/util/sysprocess/process.go @@ -0,0 +1,25 @@ +package sysprocess + +import ( + "github.com/shirou/gopsutil/process" + "os" +) + +func GetProcessNameByPID(pid int32) (string, error) { + proc, err := process.NewProcess(pid) + if err != nil { + return "", err + } + + processName, err := proc.Name() + if err != nil { + return "", err + } + + return processName, nil +} + +func GetMyProcessName() (string, error) { + return GetProcessNameByPID(int32(os.Getpid())) +} +