// ============================================================================ // procutil_windows.go — 进程检测工具(用于「启动时运行」去重) // // 提供两个检测函数: // - isExeRunning(exe) 按可执行文件名/完整路径枚举进程判断是否在运行 // - isPidAlive(pid) 用 OpenProcess + WaitForSingleObject 判断指定 PID 是否存活 // ============================================================================ package main import ( "path/filepath" "strings" "unsafe" "golang.org/x/sys/windows" ) // waitTimeoutMs Windows WaitForSingleObject 的 WAIT_TIMEOUT 返回值(进程仍在运行) const waitTimeoutMs = 0x00000102 // isExeRunning 判断指定可执行文件是否已在运行。 // exe 为程序路径(可能含目录,也可能只是裸文件名如 notepad.exe)。 // 含目录时按完整路径匹配(大小写不敏感,最准确);无目录时按进程镜像名匹配。 func isExeRunning(exe string) bool { exe = strings.TrimSpace(exe) if exe == "" { return false } target := strings.ToLower(filepath.Clean(exe)) wantFull := strings.ContainsAny(exe, `\/`) // 是否带路径 snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0) if err != nil { return false } defer windows.CloseHandle(snapshot) var entry windows.ProcessEntry32 entry.Size = uint32(unsafe.Sizeof(entry)) // 结构大小必须初始化 for err = windows.Process32First(snapshot, &entry); err == nil; err = windows.Process32Next(snapshot, &entry) { if wantFull { // 带路径:用 QueryFullProcessImageName 拿完整路径匹配 h, e := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, entry.ProcessID) if e != nil { continue } buf := make([]uint16, windows.MAX_PATH) size := uint32(len(buf)) if e := windows.QueryFullProcessImageName(h, 0, &buf[0], &size); e == nil { got := strings.ToLower(windows.UTF16ToString(buf[:size])) if got == target { windows.CloseHandle(h) return true } } windows.CloseHandle(h) } else { // 无路径:按进程镜像名(ExeFile)匹配 got := strings.ToLower(windows.UTF16ToString(entry.ExeFile[:])) if got == target { return true } } } return false } // isPidAlive 判断指定 PID 的进程是否存活。 // 进程不存在/已退出返回 false;打不开(权限)按存活处理(保守)。 func isPidAlive(pid uint32) bool { if pid == 0 { return false } h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.SYNCHRONIZE, false, pid) if err != nil { // 打开失败:可能无权限(仍可能存活)或已退出。用 ERROR_INVALID_PARAMETER // 判断进程不存在。 return err != windows.ERROR_INVALID_PARAMETER } defer windows.CloseHandle(h) // WaitForSingleObject(0):WAIT_TIMEOUT=仍运行,WAIT_OBJECT_0=已退出 rv, _ := windows.WaitForSingleObject(h, 0) return rv == waitTimeoutMs }