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