xmtop/widgets/proc_other.go

58 lines
1.5 KiB
Go
Raw Normal View History

2019-05-14 17:08:46 +08:00
// +build darwin openbsd
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"
2020-02-29 04:48:35 +08:00
"github.com/xxxserxxx/gotop/v3/utils"
)
const (
2019-03-01 08:29:52 +08:00
// Define column widths for ps output used in Procs()
five = "12345"
ten = five + five
fifty = ten + ten + ten + ten + ten
)
2019-03-12 04:35:13 +08:00
func getProcs() ([]Proc, error) {
keywords := fmt.Sprintf("pid=%s,comm=%s,pcpu=%s,pmem=%s,args", ten, fifty, five, five)
2019-02-10 22:16:12 +08:00
output, err := exec.Command("ps", "-caxo", keywords).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
2019-03-01 08:29:52 +08:00
linesOfProcStrings := strings.Split(strings.TrimSpace(string(output)), "\n")[1:]
2019-03-01 08:29:52 +08:00
procs := []Proc{}
for _, line := range linesOfProcStrings {
pid, err := strconv.Atoi(strings.TrimSpace(line[0:10]))
if err != nil {
log.Printf("failed to convert first field to int: %v. split: %v", err, line)
}
cpu, err := strconv.ParseFloat(utils.ConvertLocalizedString(strings.TrimSpace(line[63:68])), 64)
if err != nil {
log.Printf("failed to convert third field to float: %v. split: %v", err, line)
}
mem, err := strconv.ParseFloat(utils.ConvertLocalizedString(strings.TrimSpace(line[69:74])), 64)
if err != nil {
log.Printf("failed to convert fourth field to float: %v. split: %v", err, line)
}
2019-03-01 08:29:52 +08:00
proc := Proc{
2019-03-12 04:35:13 +08:00
Pid: pid,
CommandName: strings.TrimSpace(line[11:61]),
Cpu: cpu,
Mem: mem,
FullCommand: line[74:],
}
2019-03-01 08:29:52 +08:00
procs = append(procs, proc)
}
2019-03-01 08:29:52 +08:00
return procs, nil
}