2018-12-14 11:24:34 +08:00
|
|
|
// +build freebsd darwin
|
2018-12-14 11:13:28 +08:00
|
|
|
|
2018-05-16 04:13:22 +08:00
|
|
|
package widgets
|
2018-05-16 02:10:30 +08:00
|
|
|
|
|
|
|
import (
|
2018-12-14 13:59:45 +08:00
|
|
|
"fmt"
|
2018-12-05 13:44:25 +08:00
|
|
|
"log"
|
2018-05-16 02:10:30 +08:00
|
|
|
"os/exec"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2018-05-16 04:13:22 +08:00
|
|
|
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
|
|
|
|
}
|
|
|
|
|
2018-05-16 04:13:22 +08:00
|
|
|
// have to iterate like this in order to actually change the value
|
2018-12-05 13:44:25 +08:00
|
|
|
for i := range processes {
|
2018-05-16 04:13:22 +08:00
|
|
|
processes[i].CPU /= self.cpuCount
|
|
|
|
}
|
|
|
|
|
|
|
|
self.ungroupedProcs = processes
|
|
|
|
self.groupedProcs = Group(processes)
|
|
|
|
|
|
|
|
self.Sort()
|
2018-05-16 02:10:30 +08:00
|
|
|
}
|
|
|
|
|
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()
|
2018-12-05 13:44:25 +08:00
|
|
|
if err != nil {
|
2018-12-14 13:59:45 +08:00
|
|
|
return nil, fmt.Errorf("failed to execute 'ps' command: %v", err)
|
2018-12-05 13:44:25 +08:00
|
|
|
}
|
2018-12-14 11:24:34 +08:00
|
|
|
// converts to []string and removes the header
|
|
|
|
strOutput := strings.Split(strings.TrimSpace(string(output)), "\n")[1:]
|
2018-05-16 02:10:30 +08:00
|
|
|
processes := []Process{}
|
2018-12-14 11:24:34 +08:00
|
|
|
for _, line := range strOutput {
|
|
|
|
split := strings.Fields(line)
|
|
|
|
pid, err := strconv.Atoi(split[0])
|
2018-12-05 13:44:25 +08:00
|
|
|
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-05 13:44:25 +08:00
|
|
|
}
|
2018-12-14 11:24:34 +08:00
|
|
|
cpu, err := strconv.ParseFloat(split[2], 64)
|
2018-12-05 13:44:25 +08:00
|
|
|
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-05 13:44:25 +08:00
|
|
|
}
|
2018-12-14 11:24:34 +08:00
|
|
|
mem, err := strconv.ParseFloat(split[3], 64)
|
2018-12-05 13:44:25 +08:00
|
|
|
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)
|
2018-12-05 13:44:25 +08:00
|
|
|
}
|
2018-05-16 02:10:30 +08:00
|
|
|
process := Process{
|
|
|
|
PID: pid,
|
2018-12-14 11:24:34 +08:00
|
|
|
Command: split[1],
|
2018-05-16 02:10:30 +08:00
|
|
|
CPU: cpu,
|
|
|
|
Mem: mem,
|
2018-12-14 11:24:34 +08:00
|
|
|
Args: strings.Join(split[4:], " "),
|
2018-05-16 02:10:30 +08:00
|
|
|
}
|
|
|
|
processes = append(processes, process)
|
|
|
|
}
|
2018-12-14 13:59:45 +08:00
|
|
|
return processes, nil
|
2018-05-16 02:10:30 +08:00
|
|
|
}
|