package main import ( "fmt" "os" "os/exec" "strconv" "strings" ) func isProcessExist(appName string) (bool, string, int) { appary := make(map[string]int) cmd := exec.Command("cmd", "/C", "tasklist") output, _ := cmd.Output() //fmt.Printf("fields: %v\n", output) n := strings.Index(string(output), "System") if n == -1 { fmt.Println("no find") os.Exit(1) } data := string(output)[n:] fields := strings.Fields(data) for k, v := range fields { if v == appName { appary[appName], _ = strconv.Atoi(fields[k+1]) return true, appName, appary[appName] } } return false, appName, -1 } func main() { fmt.Println(isProcessExist("chrome.exe")) }
输出:
true chrome.exe 7316
查找进程并删除进程
package main import ( "fmt" "os" "os/exec" "strconv" "strings" ) func isProcessExist(appName string) (bool, string, int) { appary := make(map[string]int) cmd := exec.Command("cmd", "/C", "tasklist") output, _ := cmd.Output() //fmt.Printf("fields: %v\n", output) n := strings.Index(string(output), "System") if n == -1 { fmt.Println("no find") os.Exit(1) } data := string(output)[n:] fields := strings.Fields(data) for k, v := range fields { if v == appName { appary[appName], _ = strconv.Atoi(fields[k+1]) return true, appName, appary[appName] } } return false, appName, -1 } func main() { fmt.Println(isProcessExist("notepad++.exe")) c := exec.Command("cmd.exe", "/C", "taskkill", "/IM", "notepad++.exe") err := c.Start() if err != nil { fmt.Println(err) } c.Wait() }