2024-02-17 03:48:29 +00:00
|
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
2021-12-22 21:54:41 +00:00
|
|
|
//go:build linux || freebsd || darwin || openbsd
|
2015-10-11 21:57:53 +09:00
|
|
|
|
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2018-03-31 21:35:53 +09:00
|
|
|
"context"
|
2022-03-04 18:18:03 +02:00
|
|
|
"errors"
|
2015-10-11 21:57:53 +09:00
|
|
|
"os/exec"
|
|
|
|
"strconv"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2018-03-31 21:35:53 +09:00
|
|
|
func CallLsofWithContext(ctx context.Context, invoke Invoker, pid int32, args ...string) ([]string, error) {
|
2015-10-11 21:57:53 +09: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...)
|
2022-03-04 18:18:03 +02:00
|
|
|
out, err := invoke.CommandWithContext(ctx, "lsof", cmd...)
|
2015-10-11 21:57:53 +09:00
|
|
|
if err != nil {
|
2022-03-04 18:18:03 +02:00
|
|
|
if errors.Is(err, exec.ErrNotFound) {
|
|
|
|
return []string{}, err
|
|
|
|
}
|
2019-05-08 17:56:14 +02:00
|
|
|
// if no pid found, lsof returns code 1.
|
2015-10-11 21:57:53 +09:00
|
|
|
if err.Error() == "exit status 1" && len(out) == 0 {
|
2015-10-11 22:15:47 +09:00
|
|
|
return []string{}, nil
|
2015-10-11 21:57:53 +09: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
|
|
|
|
}
|