一个简单的Golang代码,监控windows进程退出并自动重启
这里模拟QQ退出后自动重启
只要修改
processName 为你所需要的进程exe
processNamePath 为你所需要的进程路径
package main import ( "bytes" "errors" "fmt" "os" "os/exec" "regexp" "strconv" "time" ) var processName = "QQ.exe" var processNamePath = "D:\\Program Files (x86)\\Tencent\\QQ\\Bin\\" func findProcessID(processName string) (int, error) { buf := bytes.Buffer{} cmd := exec.Command("wmic", "process", "get", "name,processid") cmd.Stdout = &buf cmd.Run() cmd2 := exec.Command("findstr", processName) cmd2.Stdin = &buf data, _ := cmd2.CombinedOutput() if len(data) == 0 { return -1, errors.New("not find") } info := string(data) reg := regexp.MustCompile(`[0-9]+`) pid := reg.FindString(info) return strconv.Atoi(pid) } func getNowTime() string { timeNow := time.Now().Format("2006-01-02 15:04:05") return timeNow } func main() { pid, err := findProcessID(processName) if pid > 0 { fmt.Println("time:", getNowTime()) fmt.Println(processName+" processID:", pid, " is running") } if err == nil { process, err := os.FindProcess(pid) if err != nil { fmt.Println("get process err:", err) return } process.Wait() } attr := &os.ProcAttr{ Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}, Env: os.Environ(), } for { _, err := findProcessID(processName) if err != nil { p, err := os.StartProcess(processNamePath+processName, []string{}, attr) if err != nil { fmt.Println("err:", err) return } fmt.Println("time:", getNowTime()) fmt.Println(processName+" restart pid:", p.Pid) p.Wait() time.Sleep(1 * time.Second) fmt.Println("start ", processName) } } }
go build xxx.go 打包成exe就可以运行了
声明:版权所有,违者必究 | 如未注明,均为原创 | 本网站采用 BY-NC-SA 协议进行授权
转载:转载请注明原文链接,违者必究 - :https://www.wolfcode.net/info/236/