Skip to content

Commit

Permalink
unix: add SysctlKinfoProc on darwin
Browse files Browse the repository at this point in the history
This allows to get KinfoProc for a given process using
SysctlKinfoProcSlice("kern.proc.pid", pid) rather than having to query
all processes using SysctlKinfoProcSlice() and the extracting the
relevant KinfoProc.

Change-Id: I965ea5c77d6f3441592b4540c54ab56f6ac9e27d
Reviewed-on: https://go-review.googlesource.com/c/sys/+/359676
Trust: Tobias Klauser <tobias.klauser@gmail.com>
Run-TryBot: Tobias Klauser <tobias.klauser@gmail.com>
TryBot-Result: Go Bot <gobot@golang.org>
Reviewed-by: Ian Lance Taylor <iant@golang.org>
  • Loading branch information
tklauser committed Nov 2, 2021
1 parent 39c9dd3 commit 95da234
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
17 changes: 17 additions & 0 deletions unix/syscall_darwin.go
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,23 @@ func GetsockoptXucred(fd, level, opt int) (*Xucred, error) {
return x, err
}

func SysctlKinfoProc(name string, args ...int) (*KinfoProc, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return nil, err
}

var kinfo KinfoProc
n := uintptr(SizeofKinfoProc)
if err := sysctl(mib, (*byte)(unsafe.Pointer(&kinfo)), &n, nil, 0); err != nil {
return nil, err
}
if n != SizeofKinfoProc {
return nil, EIO
}
return &kinfo, nil
}

func SysctlKinfoProcSlice(name string) ([]KinfoProc, error) {
mib, err := sysctlmib(name)
if err != nil {
Expand Down
11 changes: 11 additions & 0 deletions unix/syscall_darwin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,14 @@ func TestGetsockoptXucred(t *testing.T) {
}
}
}

func TestSysctlKinfoProc(t *testing.T) {
pid := unix.Getpid()
kp, err := unix.SysctlKinfoProc("kern.proc.pid", pid)
if err != nil {
t.Fatalf("SysctlKinfoProc: %v", err)
}
if got, want := int(kp.Proc.P_pid), pid; got != want {
t.Errorf("got pid %d, want %d", got, want)
}
}

0 comments on commit 95da234

Please sign in to comment.