英文:
Is there a way to find a process id on windows in Go?
问题
在操作系统包中,有一个FindProcess()函数,你可以传入进程的ID来获取一个进程。然后你可以调用kill函数来终止该进程,但是有没有一种方法可以根据进程名来查找进程呢?(在Windows系统中)
例如,我想要像这样做:
p, perr := os.FindProcessByName("Itunes")
if perr != nil {
fmt.Println(perr)
}
p.Kill()
我只需要在Windows系统上实现这个功能。
英文:
In OS package there is a FindProcess() that you can pass in the ID of the process to get a process. You can then call kill on the process but is there a way to find a process based off of the name? (In windows)
For example i would like to be able to do something like this.
p, perr := os.FindProcessByName("Itunes")
if perr != nil {
fmt.Println(perr)
}
p.Kill()
I only need this to work on Windows.
答案1
得分: 3
这是一个使用w32绑定的示例代码,它可以获取指定进程的名称。你可以使用github.com/AllenDang/w32库来实现这个功能。
package main
import (
"fmt"
"github.com/AllenDang/w32"
"unsafe"
)
func GetProcessName(id uint32) string {
snapshot := w32.CreateToolhelp32Snapshot(w32.TH32CS_SNAPMODULE, id)
if snapshot == w32.ERROR_INVALID_HANDLE {
return "<UNKNOWN>"
}
defer w32.CloseHandle(snapshot)
var me w32.MODULEENTRY32
me.Size = uint32(unsafe.Sizeof(me))
if w32.Module32First(snapshot, &me) {
return w32.UTF16PtrToString(&me.SzModule[0])
}
return "<UNKNOWN>"
}
func ListProcesses() []uint32 {
sz := uint32(1000)
procs := make([]uint32, sz)
var bytesReturned uint32
if w32.EnumProcesses(procs, sz, &bytesReturned) {
return procs[:int(bytesReturned)/4]
}
return []uint32{}
}
func FindProcessByName(name string) (uint32, error) {
for _, pid := range ListProcesses() {
if GetProcessName(pid) == name {
return pid, nil
}
}
return 0, fmt.Errorf("unknown process")
}
func main() {
fmt.Println(FindProcessByName("chrome.exe"))
}
这段代码使用了w32库中的函数来获取进程列表和进程名称。ListProcesses
函数返回一个包含所有进程ID的切片,GetProcessName
函数根据进程ID获取进程名称,FindProcessByName
函数通过遍历进程列表来查找指定名称的进程,并返回其进程ID。在main
函数中,我们调用FindProcessByName
函数来查找名为"chrome.exe"的进程,并打印出其进程ID。
英文:
It's not pretty, but you can use the w32 binding: (github.com/AllenDang/w32)
package main
import (
"fmt"
"github.com/AllenDang/w32"
"unsafe"
)
func GetProcessName(id uint32) string {
snapshot := w32.CreateToolhelp32Snapshot(w32.TH32CS_SNAPMODULE, id)
if snapshot == w32.ERROR_INVALID_HANDLE {
return "<UNKNOWN>"
}
defer w32.CloseHandle(snapshot)
var me w32.MODULEENTRY32
me.Size = uint32(unsafe.Sizeof(me))
if w32.Module32First(snapshot, &me) {
return w32.UTF16PtrToString(&me.SzModule[0])
}
return "<UNKNOWN>"
}
func ListProcesses() []uint32 {
sz := uint32(1000)
procs := make([]uint32, sz)
var bytesReturned uint32
if w32.EnumProcesses(procs, sz, &bytesReturned) {
return procs[:int(bytesReturned)/4]
}
return []uint32{}
}
func FindProcessByName(name string) (uint32, error) {
for _, pid := range ListProcesses() {
if GetProcessName(pid) == name {
return pid, nil
}
}
return 0, fmt.Errorf("unknown process")
}
func main() {
fmt.Println(FindProcessByName("chrome.exe"))
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论