2019-05-14 17:08:46 +08:00
|
|
|
package widgets
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"log"
|
|
|
|
"os/exec"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
2019-05-29 02:42:40 +08:00
|
|
|
|
2020-02-14 06:26:28 +08:00
|
|
|
"github.com/xxxserxxx/gotop/utils"
|
2019-05-14 17:08:46 +08:00
|
|
|
)
|
|
|
|
|
2019-05-14 18:43:39 +08:00
|
|
|
type processList struct {
|
2019-05-14 17:08:46 +08:00
|
|
|
ProcessInformation struct {
|
|
|
|
Process []struct {
|
2019-05-14 18:43:39 +08:00
|
|
|
Pid string `json:"pid"`
|
|
|
|
Comm string `json:"command"`
|
|
|
|
Cpu string `json:"percent-cpu" `
|
|
|
|
Mem string `json:"percent-memory" `
|
|
|
|
Args string `json:"arguments" `
|
|
|
|
} `json:"process"`
|
|
|
|
} `json:"process-information"`
|
2019-05-14 17:08:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
func getProcs() ([]Proc, error) {
|
|
|
|
output, err := exec.Command("ps", "-axo pid,comm,%cpu,%mem,args", "--libxo", "json").Output()
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to execute 'ps' command: %v", err)
|
|
|
|
}
|
|
|
|
|
2019-05-14 18:43:39 +08:00
|
|
|
list := processList{}
|
|
|
|
err = json.Unmarshal(output, &list)
|
2019-05-14 17:08:46 +08:00
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("failed to unmarshal json. %s", err)
|
|
|
|
}
|
|
|
|
procs := []Proc{}
|
|
|
|
|
2019-05-14 18:43:39 +08:00
|
|
|
for _, process := range list.ProcessInformation.Process {
|
|
|
|
if process.Comm == "idle" {
|
|
|
|
continue
|
|
|
|
}
|
2019-05-14 17:08:46 +08:00
|
|
|
pid, err := strconv.Atoi(strings.TrimSpace(process.Pid))
|
|
|
|
if err != nil {
|
|
|
|
log.Printf("failed to convert first field to int: %v. split: %v", err, process)
|
|
|
|
}
|
2019-05-29 02:42:40 +08:00
|
|
|
cpu, err := strconv.ParseFloat(utils.ConvertLocalizedString(process.Cpu), 32)
|
2019-05-14 17:08:46 +08:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("failed to convert third field to float: %v. split: %v", err, process)
|
|
|
|
}
|
2019-05-29 02:42:40 +08:00
|
|
|
mem, err := strconv.ParseFloat(utils.ConvertLocalizedString(process.Mem), 32)
|
2019-05-14 17:08:46 +08:00
|
|
|
if err != nil {
|
|
|
|
log.Printf("failed to convert fourth field to float: %v. split: %v", err, process)
|
|
|
|
}
|
|
|
|
proc := Proc{
|
|
|
|
Pid: pid,
|
|
|
|
CommandName: process.Comm,
|
|
|
|
Cpu: cpu,
|
|
|
|
Mem: mem,
|
|
|
|
FullCommand: process.Args,
|
|
|
|
}
|
|
|
|
procs = append(procs, proc)
|
|
|
|
}
|
|
|
|
|
|
|
|
return procs, nil
|
|
|
|
}
|