summaryrefslogtreecommitdiffstats
path: root/widgets/proc_linux.go
blob: b967c7bb2a292cee4fab5bf5fe8b4bff7c97bfaa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package widgets

import (
	"fmt"
	"log"
	"os/exec"
	"strconv"
	"strings"
)

func getProcs() ([]Proc, error) {
	output, err := exec.Command("ps", "-axo", "pid:10,comm:50,pcpu:5,pmem:5,args").Output()
	if err != nil {
		return nil, fmt.Errorf(tr.Value("widget.proc.err.ps", err.Error()))
	}

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

	procs := []Proc{}
	for _, line := range linesOfProcStrings {
		log.Printf("line is '%s', pid is '%s', cpu is '%s', mem is '%s'", line, strings.TrimSpace(line[0:10]), strings.TrimSpace(line[63:68]), strings.TrimSpace(line[69:74]))
		pid, err := strconv.Atoi(strings.TrimSpace(line[0:10]))
		if err != nil {
			log.Println(tr.Value("widget.proc.err.pidconv", err.Error(), line))
		}
		cpu, err := strconv.ParseFloat(strings.TrimSpace(line[63:68]), 64)
		if err != nil {
			log.Println(tr.Value("widget.proc.err.cpuconv", err.Error(), line))
		}
		mem, err := strconv.ParseFloat(strings.TrimSpace(line[69:74]), 64)
		if err != nil {
			log.Println(tr.Value("widget.proc.err.memconv", err.Error(), line))
		}
		proc := Proc{
			Pid:         pid,
			CommandName: strings.TrimSpace(line[11:61]),
			FullCommand: line[74:],
			CPU:         cpu,
			Mem:         mem,
		}
		procs = append(procs, proc)
	}

	return procs, nil
}