-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproc_bsd.go
58 lines (46 loc) · 1.04 KB
/
proc_bsd.go
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
47
48
49
50
51
52
53
54
55
56
57
58
// +build darwin freebsd netbsd openbsd
package proc
import (
"bufio"
"bytes"
"os/exec"
"strconv"
"strings"
)
func ps(args ...string) (*bytes.Buffer, error) {
var stdout bytes.Buffer
cmd := exec.Command("ps", args...)
cmd.Stdout = &stdout
if err := cmd.Run(); err != nil {
eErr, ok := err.(*exec.ExitError)
if ok && !eErr.Success() {
return &stdout, nil
}
return nil, err
}
return &stdout, nil
}
// listProcs returns a list of the running processes.
func listProcs() ([]*Proc, error) {
buf, err := ps("-x", "-o", "pid= ppid=")
if err != nil {
return nil, err
}
var procs []*Proc
scanner := bufio.NewScanner(buf)
for scanner.Scan() {
fields := strings.Fields(scanner.Text())
// If the field can't be converted to a number skip.
// It's probably the name of the column or something similar.
pid, err := strconv.Atoi(fields[0])
if err != nil {
continue
}
ppid, err := strconv.Atoi(fields[1])
if err != nil {
continue
}
procs = append(procs, &Proc{Pid: pid, Ppid: ppid})
}
return procs, scanner.Err()
}