package ProcessMonitor import ( "AudioPlayer/Common" "encoding/json" "fmt" "github.com/shirou/gopsutil/v3/process" "go-micro.dev/v5/registry" "io" "os" "path/filepath" "strings" "time" ) // 辅助函数:检查特定 PID 的进程是否存在 func processExistsByPid(pid int32) bool { _, err := process.NewProcess(pid) if err != nil { if err == process.ErrorProcessNotRunning { return false } return false } return true } type PidInfo struct { Pid int32 IdName string } func (p *PidInfo) Exists() bool { return processExistsByPid(p.Pid) } var StitchingServerPid map[int32]PidInfo func GetProcess() { // 读取文件并解析json err := Common.Micro.Register(®istry.Service{}) procs, err := process.Processes() if err != nil { return } for _, p := range procs { name, err := p.Name() if err != nil { continue } if strings.Contains(name, "StitchingServer") { if _, ok := StitchingServerPid[p.Pid]; ok { continue } cwd, err := p.Cwd() if err != nil { continue } file, err := os.OpenFile(filepath.Join(cwd, "Server", "SplicingGuide.json"), os.O_RDONLY, 0644) defer file.Close() all, err := io.ReadAll(file) if err != nil { continue } var jsondata StitchingServerServerJson err = json.Unmarshal(all, &jsondata) if err != nil { continue } err = Common.Micro.Register(®istry.Service{ Name: "omat_stitching_server", Version: "latest", Nodes: []*registry.Node{ { Id: Common.Machine + "_" + strings.Replace(fmt.Sprintf("%s_%d", jsondata.Server.Host, jsondata.Server.Port), ".", "_", -1) + "_omat_stitching_server", Address: fmt.Sprintf("%s:%d", "0.0.0.0", jsondata.Server.Port), Metadata: map[string]string{ "protocol": "http", }, }, }, }) if err != nil { continue } var keysToDelete []int32 for _, info := range StitchingServerPid { if info.Exists() { continue } // 读取文件并解析json err = Common.Micro.Deregister(®istry.Service{ Name: "omat_stitching_server", Version: "latest", Nodes: []*registry.Node{ { Id: info.IdName, }, }, }) keysToDelete = append(keysToDelete, info.Pid) } for _, key := range keysToDelete { delete(StitchingServerPid, key) } StitchingServerPid[p.Pid] = PidInfo{ Pid: p.Pid, IdName: Common.Machine + "_" + strings.Replace(fmt.Sprintf("%s_%d", jsondata.Server.Host, jsondata.Server.Port), ".", "_", -1) + "_omat_stitching_server", } } for _, info := range StitchingServerPid { info.Exists() } } return } type StitchingServerServerJson struct { Server struct { Host string `json:"Host"` Port int `json:"Port"` } `json:"Server"` } func Start() { for { GetProcess() time.Sleep(time.Second * 5) } }