blob: 750a5926d0713f337adb8b77997bb835c95930f3 [file] [log] [blame]
Serge Bazanskicc25bdf2018-10-25 14:02:58 +02001// +build linux freebsd darwin openbsd
2
3package common
4
5import (
6 "context"
7 "os/exec"
8 "strconv"
9 "strings"
10)
11
12func CallLsofWithContext(ctx context.Context, invoke Invoker, pid int32, args ...string) ([]string, error) {
13 var cmd []string
14 if pid == 0 { // will get from all processes.
15 cmd = []string{"-a", "-n", "-P"}
16 } else {
17 cmd = []string{"-a", "-n", "-P", "-p", strconv.Itoa(int(pid))}
18 }
19 cmd = append(cmd, args...)
20 lsof, err := exec.LookPath("lsof")
21 if err != nil {
22 return []string{}, err
23 }
24 out, err := invoke.CommandWithContext(ctx, lsof, cmd...)
25 if err != nil {
26 // if no pid found, lsof returnes code 1.
27 if err.Error() == "exit status 1" && len(out) == 0 {
28 return []string{}, nil
29 }
30 }
31 lines := strings.Split(string(out), "\n")
32
33 var ret []string
34 for _, l := range lines[1:] {
35 if len(l) == 0 {
36 continue
37 }
38 ret = append(ret, l)
39 }
40 return ret, nil
41}
42
43func CallPgrepWithContext(ctx context.Context, invoke Invoker, pid int32) ([]int32, error) {
44 var cmd []string
45 cmd = []string{"-P", strconv.Itoa(int(pid))}
46 pgrep, err := exec.LookPath("pgrep")
47 if err != nil {
48 return []int32{}, err
49 }
50 out, err := invoke.CommandWithContext(ctx, pgrep, cmd...)
51 if err != nil {
52 return []int32{}, err
53 }
54 lines := strings.Split(string(out), "\n")
55 ret := make([]int32, 0, len(lines))
56 for _, l := range lines {
57 if len(l) == 0 {
58 continue
59 }
60 i, err := strconv.Atoi(l)
61 if err != nil {
62 continue
63 }
64 ret = append(ret, int32(i))
65 }
66 return ret, nil
67}