procutil_windows.go 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // ============================================================================
  2. // procutil_windows.go — 进程检测工具(用于「启动时运行」去重)
  3. //
  4. // 提供两个检测函数:
  5. // - isExeRunning(exe) 按可执行文件名/完整路径枚举进程判断是否在运行
  6. // - isPidAlive(pid) 用 OpenProcess + WaitForSingleObject 判断指定 PID 是否存活
  7. // ============================================================================
  8. package main
  9. import (
  10. "path/filepath"
  11. "strings"
  12. "unsafe"
  13. "golang.org/x/sys/windows"
  14. )
  15. // waitTimeoutMs Windows WaitForSingleObject 的 WAIT_TIMEOUT 返回值(进程仍在运行)
  16. const waitTimeoutMs = 0x00000102
  17. // isExeRunning 判断指定可执行文件是否已在运行。
  18. // exe 为程序路径(可能含目录,也可能只是裸文件名如 notepad.exe)。
  19. // 含目录时按完整路径匹配(大小写不敏感,最准确);无目录时按进程镜像名匹配。
  20. func isExeRunning(exe string) bool {
  21. exe = strings.TrimSpace(exe)
  22. if exe == "" {
  23. return false
  24. }
  25. target := strings.ToLower(filepath.Clean(exe))
  26. wantFull := strings.ContainsAny(exe, `\/`) // 是否带路径
  27. snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0)
  28. if err != nil {
  29. return false
  30. }
  31. defer windows.CloseHandle(snapshot)
  32. var entry windows.ProcessEntry32
  33. entry.Size = uint32(unsafe.Sizeof(entry)) // 结构大小必须初始化
  34. for err = windows.Process32First(snapshot, &entry); err == nil; err = windows.Process32Next(snapshot, &entry) {
  35. if wantFull {
  36. // 带路径:用 QueryFullProcessImageName 拿完整路径匹配
  37. h, e := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, entry.ProcessID)
  38. if e != nil {
  39. continue
  40. }
  41. buf := make([]uint16, windows.MAX_PATH)
  42. size := uint32(len(buf))
  43. if e := windows.QueryFullProcessImageName(h, 0, &buf[0], &size); e == nil {
  44. got := strings.ToLower(windows.UTF16ToString(buf[:size]))
  45. if got == target {
  46. windows.CloseHandle(h)
  47. return true
  48. }
  49. }
  50. windows.CloseHandle(h)
  51. } else {
  52. // 无路径:按进程镜像名(ExeFile)匹配
  53. got := strings.ToLower(windows.UTF16ToString(entry.ExeFile[:]))
  54. if got == target {
  55. return true
  56. }
  57. }
  58. }
  59. return false
  60. }
  61. // isPidAlive 判断指定 PID 的进程是否存活。
  62. // 进程不存在/已退出返回 false;打不开(权限)按存活处理(保守)。
  63. func isPidAlive(pid uint32) bool {
  64. if pid == 0 {
  65. return false
  66. }
  67. h, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.SYNCHRONIZE, false, pid)
  68. if err != nil {
  69. // 打开失败:可能无权限(仍可能存活)或已退出。用 ERROR_INVALID_PARAMETER
  70. // 判断进程不存在。
  71. return err != windows.ERROR_INVALID_PARAMETER
  72. }
  73. defer windows.CloseHandle(h)
  74. // WaitForSingleObject(0):WAIT_TIMEOUT=仍运行,WAIT_OBJECT_0=已退出
  75. rv, _ := windows.WaitForSingleObject(h, 0)
  76. return rv == waitTimeoutMs
  77. }