-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocess.go
53 lines (49 loc) · 888 Bytes
/
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
package main
import (
"bytes"
"log"
"os/exec"
"strconv"
"strings"
)
type Process struct {
pid int
cpu float64
memory float64
}
func main() {
cmd := exec.Command("ps", "aux")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
log.Fatal(err)
}
processes := make([]*Process, 0)
for {
line, err := out.ReadString('\n')
if err != nil {
break
}
tokens := strings.Split(line, " ")
ft := make([]string, 0)
for _, t := range tokens {
if t != "" && t != "\t" {
ft = append(ft, t)
}
}
log.Println(len(ft), ft)
pid, err := strconv.Atoi(ft[1])
if err != nil {
continue
}
cpu, err := strconv.ParseFloat(ft[2], 64)
if err != nil {
log.Fatal(err)
}
processes = append(processes, &Process{pid, cpu})
}
for _, p := range processes {
log.Println("Process", p.pid, " takes ", p.cpu, " % of the CPU")
}
}