Check if a process exists in go way

后端 未结 7 1923
甜味超标
甜味超标 2020-12-31 02:29

If I have the PID of a process, is os.FindProcess enough to test for the existing of the process? I mean if it returns err can I assume that it\'s terminated (o

7条回答
  •  清歌不尽
    2020-12-31 02:38

    After searching for a few hours, the correct answer to know if a process is running on Windows is the following:

    func CheckProcessLife(pid int){
        cmd,_ := exec.Command("tasklist","/FI", "PID eq " + strconv.Itoa(pid)).Output()
        output := string(cmd[:])
        splitOutp := strings.Split(output, " ")
        if !(splitOutp[1] == "no") {
            time.Sleep(500 * time.Millisecond)
            fmt.Println("Process is running...")
            CheckProcessLife(pid)
        }else{
            fmt.Println("Process is no longer running.")
        }
    }
    

    You can check if the process is running with his PID or directly with his name, only change this line:

    cmd,_ := exec.Command("tasklist","/FI", "IMAGENAME eq yourprocessname.exe").Output()
    

提交回复
热议问题