2015-09-16 15:19:33 +08:00
|
|
|
// +build linux
|
|
|
|
|
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2015-09-16 15:27:19 +08:00
|
|
|
"os/exec"
|
2015-09-16 15:19:33 +08:00
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2015-09-18 12:36:13 +08:00
|
|
|
// CallLsof invokes lsof to get connection informations.
|
|
|
|
// This is same as darwin currently.
|
2015-09-16 15:19:33 +08:00
|
|
|
func CallLsof(invoke Invoker, pid int32, args ...string) ([]string, error) {
|
|
|
|
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...)
|
2015-09-16 15:27:19 +08:00
|
|
|
lsof, err := exec.LookPath("lsof")
|
|
|
|
if err != nil {
|
|
|
|
return []string{}, err
|
|
|
|
}
|
|
|
|
out, err := invoke.Command(lsof, cmd...)
|
2015-09-16 15:19:33 +08:00
|
|
|
if err != nil {
|
2015-09-18 12:36:13 +08:00
|
|
|
// if not pid found, lsof returnes code 1
|
|
|
|
if err.Error() == "exit status 1" && len(out) == 0 {
|
|
|
|
return []string{}, nil
|
|
|
|
}
|
2015-09-16 15:19:33 +08:00
|
|
|
return []string{}, err
|
|
|
|
}
|
|
|
|
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
|
|
|
|
}
|