-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathprocess.go
61 lines (53 loc) · 1.24 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
package systats
import (
"strconv"
"strings"
"github.com/dhamith93/systats/exec"
"github.com/dhamith93/systats/internal/fileops"
)
// Process holds information on single process
type Process struct {
Pid int
ExecPath string
User string
CPUUsage float32
MemUsage float32
}
func getTopProcesses(count int, sort string) ([]Process, error) {
result := exec.Execute("ps", "-eo", "pid,%cpu,%mem,user", "--no-headers", "--sort="+sort)
resultArray := strings.Split(result, "\n")
out := []Process{}
for i, process := range resultArray {
if i+1 > count {
break
}
processArray := strings.Fields(process)
if len(processArray) == 0 {
continue
}
pid, err := strconv.Atoi(processArray[0])
if err != nil {
return out, err
}
cpuUsage, err := strconv.ParseFloat(processArray[1], 32)
if err != nil {
return out, err
}
memUsage, err := strconv.ParseFloat(processArray[2], 32)
if err != nil {
return out, err
}
execPath, err := fileops.ReadFileWithError("/proc/" + processArray[0] + "/cmdline")
if err != nil {
continue
}
out = append(out, Process{
Pid: pid,
CPUUsage: float32(cpuUsage),
MemUsage: float32(memUsage),
User: processArray[3],
ExecPath: execPath,
})
}
return out, nil
}