common_unix.go 1.4 KB
Newer Older
1
// +build linux freebsd darwin openbsd
2 3 4 5

package common

import (
S
shirou 已提交
6
	"context"
7 8 9 10 11
	"os/exec"
	"strconv"
	"strings"
)

S
shirou 已提交
12
func CallLsofWithContext(ctx context.Context, invoke Invoker, pid int32, args ...string) ([]string, error) {
13 14 15 16 17 18 19 20 21 22 23
	var cmd []string
	if pid == 0 { // will get from all processes.
		cmd = []string{"-a", "-n", "-P"}
	} else {
		cmd = []string{"-a", "-n", "-P", "-p", strconv.Itoa(int(pid))}
	}
	cmd = append(cmd, args...)
	lsof, err := exec.LookPath("lsof")
	if err != nil {
		return []string{}, err
	}
S
shirou 已提交
24
	out, err := invoke.CommandWithContext(ctx, lsof, cmd...)
25
	if err != nil {
26
		// if no pid found, lsof returns code 1.
27
		if err.Error() == "exit status 1" && len(out) == 0 {
S
Shirou WAKAYAMA 已提交
28
			return []string{}, nil
29 30 31 32 33 34 35 36 37 38 39 40 41
		}
	}
	lines := strings.Split(string(out), "\n")

	var ret []string
	for _, l := range lines[1:] {
		if len(l) == 0 {
			continue
		}
		ret = append(ret, l)
	}
	return ret, nil
}
42

S
shirou 已提交
43
func CallPgrepWithContext(ctx context.Context, invoke Invoker, pid int32) ([]int32, error) {
44
	cmd := []string{"-P", strconv.Itoa(int(pid))}
45 46 47 48
	pgrep, err := exec.LookPath("pgrep")
	if err != nil {
		return []int32{}, err
	}
S
shirou 已提交
49
	out, err := invoke.CommandWithContext(ctx, pgrep, cmd...)
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
	if err != nil {
		return []int32{}, err
	}
	lines := strings.Split(string(out), "\n")
	ret := make([]int32, 0, len(lines))
	for _, l := range lines {
		if len(l) == 0 {
			continue
		}
		i, err := strconv.Atoi(l)
		if err != nil {
			continue
		}
		ret = append(ret, int32(i))
	}
	return ret, nil
}