Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[process][darwin] Fix #925 properly and improve some tests #947

Merged
merged 3 commits into from
Oct 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 3 additions & 19 deletions process/process_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"strconv"
"strings"
"time"
"unsafe"

"github.com/shirou/gopsutil/cpu"
"github.com/shirou/gopsutil/internal/common"
Expand Down Expand Up @@ -602,24 +601,9 @@ func parseKinfoProc(buf []byte) (KinfoProc, error) {
// Returns a proc as defined here:
// http://unix.superglobalmegacorp.com/Net2/newsrc/sys/kinfo_proc.h.html
func (p *Process) getKProc() (*KinfoProc, error) {
return p.getKProcWithContext(context.Background())
}

func (p *Process) getKProcWithContext(ctx context.Context) (*KinfoProc, error) {
mib := []int32{CTLKern, KernProc, KernProcPID, p.Pid}
procK := KinfoProc{}
length := uint64(unsafe.Sizeof(procK))
buf := make([]byte, length)
_, _, syserr := unix.Syscall6(
202, // unix.SYS___SYSCTL https://github.com/golang/sys/blob/76b94024e4b621e672466e8db3d7f084e7ddcad2/unix/zsysnum_darwin_amd64.go#L146
uintptr(unsafe.Pointer(&mib[0])),
uintptr(len(mib)),
uintptr(unsafe.Pointer(&buf[0])),
uintptr(unsafe.Pointer(&length)),
0,
0)
if syserr != 0 {
return nil, syserr
buf, err := unix.SysctlRaw("kern.proc.pid", int(p.Pid))
if err != nil {
return nil, err
}
k, err := parseKinfoProc(buf)
if err != nil {
Expand Down
25 changes: 25 additions & 0 deletions process/process_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,10 @@ func Test_Process_Ppid(t *testing.T) {
if v == 0 {
t.Errorf("return value is 0 %v", v)
}
expected := os.Getppid()
if v != int32(expected) {
t.Errorf("return value is %v, expected %v", v, expected)
}
}

func Test_Process_Status(t *testing.T) {
Expand Down Expand Up @@ -658,3 +662,24 @@ func Test_AllProcesses_cmdLine(t *testing.T) {
}
}
}

func BenchmarkNewProcess(b *testing.B) {
checkPid := os.Getpid()
for i := 0; i < b.N; i++ {
NewProcess(int32(checkPid))
}
}

func BenchmarkProcessName(b *testing.B) {
p := testGetProcess()
for i := 0; i < b.N; i++ {
p.Name()
}
}

func BenchmarkProcessPpid(b *testing.B) {
p := testGetProcess()
for i := 0; i < b.N; i++ {
p.Ppid()
}
}