ZBLOG

golang windows 遍历进程

在Golang中,可以使用syscall包的CreateToolhelp32SnapshotProcess32Next函数来遍历Windows进程。

package main

import (
    "fmt"
    "syscall"
    "unsafe"
)

const (
    TH32CS_SNAPPROCESS = 0x00000002
)

type PROCESSENTRY32 struct {
    dwSize              uint32
    cntUsage            uint32
    th32ProcessID       uint32
    th32DefaultHeapID   uintptr
    th32ModuleID        uint32
    cntThreads          uint32
    th32ParentProcessID uint32
    pcPriClassBase      int32
    dwFlags             uint32
    szExeFile           [260]byte // MAX_PATH = 260
}

func main() {
    hSnap := syscall.CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
    if hSnap == syscall.InvalidHandle {
        fmt.Println("Failed to create snapshot")
        return
    }
    
     var procEntry PROCESSENTRY32 
     procEntry.dwSize = unsafe.Sizeof(procEntry)
     
     err := syscall.Process32First(hSnap, &procEntry)
     if err != nil {
         fmt.Printf("Error: %v\n", err)
         return 
     }
     
     for {
         fmt.Printf("PID: %d, Name: %s\n", procEntry.th32ProcessID, string(procEntry.szExeFile[:]))
         
         err = syscall.Process32Next(hSnap, &procEntry)
         if err != nil {
             break 
         }
     }
     
     _ = syscall.CloseHandle(hSnap) 
}

运行以上代码会输出当前计算机上所有进程的PID和名称。

本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
转载请注明出处:https://golang.0voice.com/?id=4231

分享:
扫描分享到社交APP
上一篇
下一篇
发表列表
游客 游客
此处应有掌声~
评论列表

还没有评论,快来说点什么吧~

联系我们

在线咨询: 点击这里给我发消息

微信号:3007537140

上班时间: 10:30-22:30

关注我们
x

注册

已经有帐号?