gpt4 book ai didi

windows - windows环境下如何通过进程名获取进程id?

转载 作者:IT王子 更新时间:2023-10-29 01:27:50 70 4
gpt4 key购买 nike

我想在windows环境下通过进程名获取进程id?

我发现 golang 只有 api os.FindProcess(id),但没有名字。

最佳答案

我也不得不为此苦苦挣扎,并且发现解决问题的方法不是很简单,因为... WinApi :)

最后,您必须使用 CreateToolhelp32Snapshot 创建当前 Windows 进程列表的快照。然后使用 Process32First 获取快照中的第一个进程。之后继续使用 Process32Next 遍历列表,直到出现 ERROR_NO_MORE_FILES 错误。只有这样,您才能拥有整个流程列表。

参见 how2readwindowsprocesses一个工作示例。

这里是要点:

const TH32CS_SNAPPROCESS = 0x00000002

type WindowsProcess struct {
ProcessID int
ParentProcessID int
Exe string
}

func processes() ([]WindowsProcess, error) {
handle, err := windows.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
if err != nil {
return nil, err
}
defer windows.CloseHandle(handle)

var entry windows.ProcessEntry32
entry.Size = uint32(unsafe.Sizeof(entry))
// get the first process
err = windows.Process32First(handle, &entry)
if err != nil {
return nil, err
}

results := make([]WindowsProcess, 0, 50)
for {
results = append(results, newWindowsProcess(&entry))

err = windows.Process32Next(handle, &entry)
if err != nil {
// windows sends ERROR_NO_MORE_FILES on last process
if err == syscall.ERROR_NO_MORE_FILES {
return results, nil
}
return nil, err
}
}
}

func findProcessByName(processes []WindowsProcess, name string) *WindowsProcess {
for _, p := range processes {
if strings.ToLower(p.Exe) == strings.ToLower(name) {
return &p
}
}
return nil
}

func newWindowsProcess(e *windows.ProcessEntry32) WindowsProcess {
// Find when the string ends for decoding
end := 0
for {
if e.ExeFile[end] == 0 {
break
}
end++
}

return WindowsProcess{
ProcessID: int(e.ProcessID),
ParentProcessID: int(e.ParentProcessID),
Exe: syscall.UTF16ToString(e.ExeFile[:end]),
}
}

关于windows - windows环境下如何通过进程名获取进程id?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36333896/

70 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com