2016-11-22 06:18:52 +08:00
|
|
|
// +build linux freebsd darwin openbsd
|
2015-10-11 20:57:53 +08:00
|
|
|
|
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2018-03-31 20:35:53 +08:00
|
|
|
"context"
|
2015-10-11 20:57:53 +08:00
|
|
|
"os/exec"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2018-03-31 20:35:53 +08:00
|
|
|
func CallLsofWithContext(ctx context.Context, invoke Invoker, pid int32, args ...string) ([]string, error) {
|
2015-10-11 20:57:53 +08:00
|
|
|
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
|
|
|
|
}
|
2018-03-31 20:35:53 +08:00
|
|
|
out, err := invoke.CommandWithContext(ctx, lsof, cmd...)
|
2015-10-11 20:57:53 +08:00
|
|
|
if err != nil {
|
2019-05-08 23:56:14 +08:00
|
|
|
// if no pid found, lsof returns code 1.
|
2015-10-11 20:57:53 +08:00
|
|
|
if err.Error() == "exit status 1" && len(out) == 0 {
|
2015-10-11 21:15:47 +08:00
|
|
|
return []string{}, nil
|
2015-10-11 20:57:53 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
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
|
|
|
|
}
|
2015-11-23 23:04:20 +08:00
|
|
|
|
2018-03-31 20:35:53 +08:00
|
|
|
func CallPgrepWithContext(ctx context.Context, invoke Invoker, pid int32) ([]int32, error) {
|
2021-08-18 21:50:02 +08:00
|
|
|
cmd := []string{"-P", strconv.Itoa(int(pid))}
|
2015-11-23 23:04:20 +08:00
|
|
|
pgrep, err := exec.LookPath("pgrep")
|
|
|
|
if err != nil {
|
|
|
|
return []int32{}, err
|
|
|
|
}
|
2018-03-31 20:35:53 +08:00
|
|
|
out, err := invoke.CommandWithContext(ctx, pgrep, cmd...)
|
2015-11-23 23:04:20 +08:00
|
|
|
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
|
|
|
|
}
|