Skip to content
This repository has been archived by the owner on Aug 29, 2020. It is now read-only.

Commit

Permalink
Fix ps whitespace parsing errors
Browse files Browse the repository at this point in the history
  • Loading branch information
cjbassi committed Dec 7, 2018
1 parent 44ed6e8 commit 23fdf43
Showing 1 changed file with 14 additions and 13 deletions.
27 changes: 14 additions & 13 deletions src/widgets/proc_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,33 +23,34 @@ func (self *Proc) update() {
}

func Processes() []Process {
output, err := exec.Command("ps", "-axo", "pid,comm:50,pcpu,pmem,args").Output()
output, err := exec.Command("ps", "-axo", "pid:10,comm:50,pcpu:5,pmem:5,args").Output()
if err != nil {
log.Printf("failed to execute 'ps' command: %v", err)
}
// converts to []string and removes the header
strOutput := strings.Split(strings.TrimSpace(string(output)), "\n")[1:]

// converts to []string, removing trailing newline and header
processStrArr := strings.Split(strings.TrimSuffix(string(output), "\n"), "\n")[1:]

processes := []Process{}
for _, line := range strOutput {
split := strings.Fields(line)
pid, err := strconv.Atoi(split[0])
for _, line := range processStrArr {
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, split)
log.Printf("failed to convert PID to int: %v. line: %v", err, line)
}
cpu, err := strconv.ParseFloat(split[2], 64)
cpu, err := strconv.ParseFloat(strings.TrimSpace(line[63:68]), 64)
if err != nil {
log.Printf("failed to convert third field to float: %v. split: %v", err, split)
log.Printf("failed to convert CPU usage to float: %v. line: %v", err, line)
}
mem, err := strconv.ParseFloat(split[3], 64)
mem, err := strconv.ParseFloat(strings.TrimSpace(line[69:74]), 64)
if err != nil {
log.Printf("failed to convert fourth field to float: %v. split: %v", err, split)
log.Printf("failed to convert Mem usage to float: %v. line: %v", err, line)
}
process := Process{
PID: pid,
Command: split[1],
Command: strings.TrimSpace(line[11:61]),
CPU: cpu,
Mem: mem,
Args: strings.Join(split[4:], " "),
Args: line[74:],
}
processes = append(processes, process)
}
Expand Down

0 comments on commit 23fdf43

Please sign in to comment.