common_unix.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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 returns 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. cmd := []string{"-P", strconv.Itoa(int(pid))}
  40. pgrep, err := exec.LookPath("pgrep")
  41. if err != nil {
  42. return []int32{}, err
  43. }
  44. out, err := invoke.CommandWithContext(ctx, pgrep, cmd...)
  45. if err != nil {
  46. return []int32{}, err
  47. }
  48. lines := strings.Split(string(out), "\n")
  49. ret := make([]int32, 0, len(lines))
  50. for _, l := range lines {
  51. if len(l) == 0 {
  52. continue
  53. }
  54. i, err := strconv.Atoi(l)
  55. if err != nil {
  56. continue
  57. }
  58. ret = append(ret, int32(i))
  59. }
  60. return ret, nil
  61. }