mirror of https://github.com/shirou/gopsutil
Merge pull request #757 from Lomanic/darwin-process-exe-cgo-implementation
[darwin][process] Add cgo implementation of Exe() from PR #243issue734
commit
d3cd09021b
@ -0,0 +1,30 @@
|
|||||||
|
// +build darwin
|
||||||
|
// +build cgo
|
||||||
|
|
||||||
|
package process
|
||||||
|
|
||||||
|
// #include <stdlib.h>
|
||||||
|
// #include <libproc.h>
|
||||||
|
import "C"
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"unsafe"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (p *Process) ExeWithContext(ctx context.Context) (string, error) {
|
||||||
|
var c C.char // need a var for unsafe.Sizeof need a var
|
||||||
|
const bufsize = C.PROC_PIDPATHINFO_MAXSIZE * unsafe.Sizeof(c)
|
||||||
|
buffer := (*C.char)(C.malloc(C.size_t(bufsize)))
|
||||||
|
defer C.free(unsafe.Pointer(buffer))
|
||||||
|
|
||||||
|
ret, err := C.proc_pidpath(C.int(p.Pid), unsafe.Pointer(buffer), C.uint32_t(bufsize))
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
if ret <= 0 {
|
||||||
|
return "", fmt.Errorf("unknown error: proc_pidpath returned %d", ret)
|
||||||
|
}
|
||||||
|
|
||||||
|
return C.GoString(buffer), nil
|
||||||
|
}
|
@ -0,0 +1,34 @@
|
|||||||
|
// +build darwin
|
||||||
|
// +build !cgo
|
||||||
|
|
||||||
|
package process
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"fmt"
|
||||||
|
"os/exec"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (p *Process) ExeWithContext(ctx context.Context) (string, error) {
|
||||||
|
lsof_bin, err := exec.LookPath("lsof")
|
||||||
|
if err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
out, err := invoke.CommandWithContext(ctx, lsof_bin, "-p", strconv.Itoa(int(p.Pid)), "-Fpfn")
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("bad call to lsof: %s", err)
|
||||||
|
}
|
||||||
|
txtFound := 0
|
||||||
|
lines := strings.Split(string(out), "\n")
|
||||||
|
for i := 1; i < len(lines); i += 2 {
|
||||||
|
if lines[i] == "ftxt" {
|
||||||
|
txtFound++
|
||||||
|
if txtFound == 2 {
|
||||||
|
return lines[i-1][1:], nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("missing txt data returned by lsof")
|
||||||
|
}
|
Loading…
Reference in New Issue