Skip to content

Instantly share code, notes, and snippets.

@henkman
Created July 10, 2012 14:01
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save henkman/3083408 to your computer and use it in GitHub Desktop.
Save henkman/3083408 to your computer and use it in GitHub Desktop.
package main
import (
"github.com/AllenDang/w32"
"io"
"os"
"unsafe"
"errors"
"fmt"
"syscall"
)
func printModuleInfo(out io.Writer, me32 *w32.MODULEENTRY32) {
fmt.Fprintf(out, "\t%s\n", syscall.UTF16ToString(me32.SzModule[:]))
// fmt.Printf(out, "Exe: %s\n", syscall.UTF16ToString(me32.SzExePath[:]))
}
func printProcessInfo(out io.Writer, pid uint32) error {
snap := w32.CreateToolhelp32Snapshot(w32.TH32CS_SNAPMODULE, pid)
if snap == 0 {
return errors.New("snapshot could not be created")
}
defer w32.CloseHandle(snap)
var me32 w32.MODULEENTRY32
me32.Size = uint32(unsafe.Sizeof(me32))
if !w32.Module32First(snap, &me32) {
return errors.New("module information retrieval failed")
}
fmt.Fprintf(out, "pid:%d\n", pid)
printModuleInfo(out, &me32)
for w32.Module32Next(snap, &me32) {
printModuleInfo(out, &me32)
}
return nil
}
func main() {
ps := make([]uint32, 255)
var read uint32 = 0
if !w32.EnumProcesses(ps, uint32(len(ps)), &read) {
println("could not read processes")
return
}
for _, p := range ps[:read / 4] {
if p == 0 {
continue
}
err := printProcessInfo(os.Stdout, p)
if err != nil {
println(err.Error())
}
}
}
@Lomanic
Copy link

Lomanic commented Nov 12, 2017

This code will only retrieve maximum 63 running processes (255/4), you should check if ps is full and call again w32.EnumProcesses with a bigger allocated ps, see shirou/gopsutil#454

@juliusmh
Copy link

Line 43 should be

if !w32.EnumProcesses(ps, 4 * uint32(len(ps)), &read) {

because DWORD is 4 byte (but I'm sure you know this and this is just quick and dirty 😉)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment