xmtop/src/widgets/proc_other.go

64 lines
1.5 KiB
Go
Raw Normal View History

2018-12-14 11:24:34 +08:00
// +build freebsd darwin
2018-12-14 11:13:28 +08:00
package widgets
import (
2018-12-14 13:59:45 +08:00
"fmt"
"log"
"os/exec"
"strconv"
"strings"
)
func (self *Proc) update() {
2018-12-14 13:59:45 +08:00
processes, err := Processes()
if err != nil {
log.Printf("failed to retrieve processes: %v", err)
return
}
// have to iterate like this in order to actually change the value
for i := range processes {
processes[i].CPU /= self.cpuCount
}
self.ungroupedProcs = processes
self.groupedProcs = Group(processes)
self.Sort()
}
2018-12-14 13:59:45 +08:00
func Processes() ([]Process, error) {
2019-01-26 07:35:02 +08:00
output, err := exec.Command("ps", "-caxo", "pid,comm,pcpu,pmem,args").Output()
if err != nil {
2018-12-14 13:59:45 +08:00
return nil, fmt.Errorf("failed to execute 'ps' command: %v", err)
}
2018-12-14 11:24:34 +08:00
// converts to []string and removes the header
strOutput := strings.Split(strings.TrimSpace(string(output)), "\n")[1:]
processes := []Process{}
2018-12-14 11:24:34 +08:00
for _, line := range strOutput {
split := strings.Fields(line)
pid, err := strconv.Atoi(split[0])
if err != nil {
2018-12-14 11:24:34 +08:00
log.Printf("failed to convert first field to int: %v. split: %v", err, split)
}
2018-12-14 11:24:34 +08:00
cpu, err := strconv.ParseFloat(split[2], 64)
if err != nil {
2018-12-14 11:24:34 +08:00
log.Printf("failed to convert third field to float: %v. split: %v", err, split)
}
2018-12-14 11:24:34 +08:00
mem, err := strconv.ParseFloat(split[3], 64)
if err != nil {
2018-12-14 11:24:34 +08:00
log.Printf("failed to convert fourth field to float: %v. split: %v", err, split)
}
process := Process{
PID: pid,
2018-12-14 11:24:34 +08:00
Command: split[1],
CPU: cpu,
Mem: mem,
2018-12-14 11:24:34 +08:00
Args: strings.Join(split[4:], " "),
}
processes = append(processes, process)
}
2018-12-14 13:59:45 +08:00
return processes, nil
}