Fix ps whitespace parsing errors

This commit is contained in:
Caleb Bassi 2018-12-07 12:33:46 -08:00
parent 44ed6e8752
commit 23fdf43936
1 changed files with 14 additions and 13 deletions

View File

@ -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)
}