-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathprocess.go
62 lines (53 loc) · 1.63 KB
/
process.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
// Copyright 2013 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ps
import (
"syscall"
"unsafe"
"github.com/alexbrainman/ps/winapi"
)
// Process is used to query process statistics
type Process struct {
Handle syscall.Handle // process handle
closeHandle bool // if process handle needs to be close or not
}
// OpenProcess establishes access to OS process idenified by pid.
func OpenProcess(pid int) (*Process, error) {
h, err := syscall.OpenProcess(syscall.PROCESS_QUERY_INFORMATION, false, uint32(pid))
if err != nil {
return nil, err
}
return &Process{Handle: h, closeHandle: true}, nil
}
// OpenCurrent establishes access to current OS process.
func OpenCurrent() (*Process, error) {
h, err := syscall.GetCurrentProcess()
if err != nil {
return nil, err
}
return &Process{Handle: h, closeHandle: false}, nil
}
// Close closes process handle.
func (p *Process) Close() error {
return syscall.CloseHandle(p.Handle)
}
// ProcessStats stores process statistics.
type ProcessStats struct {
CPU syscall.Rusage
Memory winapi.PROCESS_MEMORY_COUNTERS
}
// Stats retrieves CPU and memory usage for process p.
// Stats can be used even for a completed process.
func (p *Process) Stats() (*ProcessStats, error) {
var s ProcessStats
err := syscall.GetProcessTimes(p.Handle, &s.CPU.CreationTime, &s.CPU.ExitTime, &s.CPU.KernelTime, &s.CPU.UserTime)
if err != nil {
return nil, err
}
err = winapi.GetProcessMemoryInfo(p.Handle, &s.Memory, uint32(unsafe.Sizeof(s.Memory)))
if err != nil {
return nil, err
}
return &s, nil
}