Golang如何通过进程名称获取进程ID?

Dev*_*hou 6 go

我想通过Windows环境中的进程名称获取进程ID?

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

Den*_*eck 6

我也不得不努力解决这个问题,并发现解决方案不是很简单,因为 \xe2\x80\xa6 WinApi :)

\n\n

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

\n\n

有关工作示例,请参阅how2readwindowsprocesses 。

\n\n

要点如下:

\n\n
const TH32CS_SNAPPROCESS = 0x00000002\n\ntype WindowsProcess struct {\n    ProcessID       int\n    ParentProcessID int\n    Exe             string\n}\n\nfunc processes() ([]WindowsProcess, error) {\n    handle, err := windows.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)\n    if err != nil {\n        return nil, err\n    }\n    defer windows.CloseHandle(handle)\n\n    var entry windows.ProcessEntry32\n    entry.Size = uint32(unsafe.Sizeof(entry))\n    // get the first process\n    err = windows.Process32First(handle, &entry)\n    if err != nil {\n        return nil, err\n    }\n\n    results := make([]WindowsProcess, 0, 50)\n    for {\n        results = append(results, newWindowsProcess(&entry))\n\n        err = windows.Process32Next(handle, &entry)\n        if err != nil {\n            // windows sends ERROR_NO_MORE_FILES on last process\n            if err == syscall.ERROR_NO_MORE_FILES {\n                return results, nil\n            }\n            return nil, err\n        }\n    }\n}\n\nfunc findProcessByName(processes []WindowsProcess, name string) *WindowsProcess {\n    for _, p := range processes {\n        if strings.ToLower(p.Exe) == strings.ToLower(name) {\n            return &p\n        }\n    }\n    return nil\n}\n\nfunc newWindowsProcess(e *windows.ProcessEntry32) WindowsProcess {\n    // Find when the string ends for decoding\n    end := 0\n    for {\n        if e.ExeFile[end] == 0 {\n            break\n        }\n        end++\n    }\n\n    return WindowsProcess{\n        ProcessID:       int(e.ProcessID),\n        ParentProcessID: int(e.ParentProcessID),\n        Exe:             syscall.UTF16ToString(e.ExeFile[:end]),\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n


flu*_*ter 2

你可以列出所有进程,并将它们与你想要查找的名称相匹配,通过使用更新的 sys 调用包,https://godoc.org/golang.org/x/sys,它拥有大部分 Windows api。

func Process32First(snapshot Handle, procEntry *ProcessEntry32) (err error)
func Process32Next(snapshot Handle, procEntry *ProcessEntry32) (err error)
Run Code Online (Sandbox Code Playgroud)

另请参阅 msdn 文档: https://msdn.microsoft.com/en-us/library/windows/desktop/ms684834 (v=vs.85).aspx