-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpsutils.go
More file actions
39 lines (32 loc) · 986 Bytes
/
psutils.go
File metadata and controls
39 lines (32 loc) · 986 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package main
import (
"fmt"
"strings"
"syscall"
"unsafe"
"golang.org/x/sys/windows"
)
func FindProcessID(processName string) (uint32, error) {
snapshot, _, _ := createToolhelp32Snapshot.Call(uintptr(TH32CS_SNAPPROCESS), 0)
if snapshot == 0 {
return 0, fmt.Errorf("failed to create snapshot. Error: %d", syscall.GetLastError())
}
defer syscall.CloseHandle(syscall.Handle(snapshot))
var entry windows.ProcessEntry32
entry.Size = uint32(unsafe.Sizeof(entry))
ret, _, _ := process32FirstW.Call(snapshot, uintptr(unsafe.Pointer(&entry)))
if ret == 0 {
return 0, fmt.Errorf("failed to retrieve first process entry. Error: %d", syscall.GetLastError())
}
for {
exeFile := windows.UTF16ToString(entry.ExeFile[:])
if strings.EqualFold(exeFile, processName) {
return entry.ProcessID, nil
}
ret, _, _ := process32NextW.Call(snapshot, uintptr(unsafe.Pointer(&entry)))
if ret == 0 {
break
}
}
return 0, fmt.Errorf("process not found: %s", processName)
}