Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Define commands build for Windows platforms
package commands
import (
"encoding/json"
"log"
"os"
"syscall"
"unsafe"
)
func CallNativeAPI(task string) (string, int, int) {
switch task {
case "ps":
log.Print("Running Task")
return getProcesses()
}
return "not implemented", 1, os.Getpid()
}
type WindowsProcess struct {
ProcessID int
ParentProcessID int
ExeFile string
}
func getProcesses() (string, int, int) {
procs, _ := getProcessWindowsProcesses()
data, err := json.Marshal(procs)
if err != nil {
log.Print("Failed")
return "Failed serializing processes", 1, os.Getpid()
}
return string(data), 0, os.Getpid()
}
func getProcessWindowsProcesses() ([]WindowsProcess, error) {
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
if err != nil {
return nil, err
}
defer syscall.CloseHandle(snapshot)
var procEntry syscall.ProcessEntry32
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
if err = syscall.Process32First(snapshot, &procEntry); err != nil {
return nil, err
}
processes := make([]WindowsProcess, 0, 100)
for {
processes = append(processes, newWindowsProcess(&procEntry))
if err = syscall.Process32Next(snapshot, &procEntry); err != nil {
if err == syscall.ERROR_NO_MORE_FILES {
break
}
}
}
return processes, nil
}
func newWindowsProcess(e *syscall.ProcessEntry32) WindowsProcess {
end := getProcessNameLength(e)
return WindowsProcess{
ProcessID: int(e.ProcessID),
ParentProcessID: int(e.ParentProcessID),
ExeFile: syscall.UTF16ToString(e.ExeFile[:end]),
}
}
func getProcessNameLength(e *syscall.ProcessEntry32) int {
size := 0
for _, char := range e.ExeFile {
if char == 0 {
break
}
size++
}
return size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment