-
Notifications
You must be signed in to change notification settings - Fork 1
/
proc_darwin.go
131 lines (99 loc) · 2.51 KB
/
proc_darwin.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
// +build darwin
package proc
// Based on https://github.com/cloudfoundry/gosigar/blob/master/sigar_darwin.go
/*
#include <sys/sysctl.h>
typedef struct kinfo_proc kInfoProc;
*/
import "C"
import (
"bytes"
"encoding/binary"
"io"
"strings"
"syscall"
"unsafe"
)
func ps(pid int) []*ProcessInfo {
processes := []*ProcessInfo{}
mib := []C.int{C.CTL_KERN, C.KERN_PROC, C.KERN_PROC_ALL, 0}
length := uintptr(0)
if err := sysctl(mib, nil, &length, nil, 0); err != nil {
return nil
}
buf := make([]byte, length)
if err := sysctl(mib, &buf[0], &length, nil, 0); err != nil {
return nil
}
kInfoProcSize := int(unsafe.Sizeof(C.kInfoProc{}))
count := int(length) / kInfoProcSize
for i := 0; i < count; i++ {
proc := (*C.kInfoProc) (unsafe.Pointer(&buf[i * kInfoProcSize]))
procPid := int(proc.kp_proc.p_pid)
if pid >= 0 && procPid != pid {
continue
}
process := ProcessInfo{Pid: procPid}
command, argv, err := kern_procargs(process.Pid)
if err != nil {
continue
}
commandParts := strings.Split(command, "/")
process.Command = strings.TrimSpace(commandParts[len(commandParts) - 1])
process.CommandLine = argv
processes = append(processes, &process)
if process.Pid == pid {
break
}
}
return processes
}
func kern_procargs(pid int) (command string, argv []string, err error) {
mib := []C.int{C.CTL_KERN, C.KERN_PROCARGS2, C.int(pid)}
argmax := uintptr(C.ARG_MAX)
buf := make([]byte, argmax)
err = sysctl(mib, &buf[0], &argmax, nil, 0)
if err != nil {
return
}
bbuf := bytes.NewBuffer(buf)
bbuf.Truncate(int(argmax))
var argc int32
binary.Read(bbuf, binary.LittleEndian, &argc)
path, err := bbuf.ReadBytes(0)
command = string(chop(path))
// skip trailing \0's
for {
c, _ := bbuf.ReadByte()
if c != 0 {
bbuf.UnreadByte()
break // start of argv[0]
}
}
argv = make([]string, argc)
for i := 0; i < int(argc); i++ {
arg, err := bbuf.ReadBytes(0)
if err == io.EOF {
break
}
argv[i] = string(chop(arg))
}
return
}
func sysctl(mib []C.int, old *byte, oldlen *uintptr, new *byte, newlen uintptr) (err error) {
_, _, e1 := syscall.Syscall6(
syscall.SYS___SYSCTL,
uintptr(unsafe.Pointer(&mib[0])),
uintptr(len(mib)),
uintptr(unsafe.Pointer(old)),
uintptr(unsafe.Pointer(oldlen)),
uintptr(unsafe.Pointer(new)),
uintptr(newlen))
if e1 != 0 {
err = e1
}
return
}
func chop(buf []byte) []byte {
return buf[0 : len(buf)-1]
}