xmtop/widgets/proc_freebsd.go

70 lines
1.7 KiB
Go
Raw Normal View History

2019-05-14 17:08:46 +08:00
package widgets
import (
"encoding/json"
"fmt"
"log"
"os/exec"
"strconv"
"strings"
2020-04-24 03:07:08 +08:00
"github.com/xxxserxxx/gotop/v4/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" `
2019-05-14 18:43:39 +08:00
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 {
2020-06-21 05:47:48 +08:00
return nil, fmt.Errorf(tr.Value("widget.proc.err.ps", err.Error()))
2019-05-14 17:08:46 +08:00
}
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 {
2020-06-21 05:47:48 +08:00
return nil, fmt.Errorf(tr.Value("widget.proc.err.parse", err.Error()))
2019-05-14 17:08:46 +08:00
}
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 {
2020-06-22 23:23:10 +08:00
sp := fmt.Sprintf("%v", process)
log.Printf(tr.Value("widget.proc.err.pidconv", err.Error(), sp))
2019-05-14 17:08:46 +08:00
}
cpu, err := strconv.ParseFloat(utils.ConvertLocalizedString(process.CPU), 32)
2019-05-14 17:08:46 +08:00
if err != nil {
2020-06-22 23:23:10 +08:00
sp := fmt.Sprintf("%v", process)
log.Printf(tr.Value("widget.proc.err.cpuconv", err.Error(), sp))
2019-05-14 17:08:46 +08:00
}
mem, err := strconv.ParseFloat(utils.ConvertLocalizedString(process.Mem), 32)
2019-05-14 17:08:46 +08:00
if err != nil {
2020-06-22 23:23:10 +08:00
sp := fmt.Sprintf("%v", process)
log.Printf(tr.Value("widget.proc.err.memconv", err.Error(), sp))
2019-05-14 17:08:46 +08:00
}
proc := Proc{
Pid: pid,
CommandName: process.Comm,
CPU: cpu,
2019-05-14 17:08:46 +08:00
Mem: mem,
FullCommand: process.Args,
}
procs = append(procs, proc)
}
return procs, nil
}