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