This article describes the way to get CPU usage of the system process under Linux through the Go language. Share to everyone for your reference. The specific analysis is as follows:
This code uses Linux's System command PS to analyze CPU usage, as follows:
Copy Code code as follows:
Package Main
Import (
"Bytes"
"Log"
"Os/exec"
"StrConv"
"Strings"
)
Type Process struct {
PID int
CPU 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")
}
}
I hope this article will help you with your go language program.