common_unix.go 1.5 KB

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