unix: allow passing optional args to SysctlKinfoProcSlice

This allows using SysctlKinfoProcSlice to e.g. query processes by user
id using the kern.proc.uid sysctl and is still backwards compatible to
original implementation, i.e. still allows the kern.proc.all sysctl
without any additional arguments.

Change-Id: Ia2d76ce5b91a077221891e1f2dfd79a38d2be52b
Reviewed-on: https://go-review.googlesource.com/c/sys/+/359677
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>
This commit is contained in:
Tobias Klauser
2021-11-01 15:23:15 +01:00
committed by Tobias Klauser
parent 95da234e12
commit a2f17f7b99
2 changed files with 27 additions and 2 deletions

View File

@@ -447,8 +447,8 @@ func SysctlKinfoProc(name string, args ...int) (*KinfoProc, error) {
return &kinfo, nil
}
func SysctlKinfoProcSlice(name string) ([]KinfoProc, error) {
mib, err := sysctlmib(name)
func SysctlKinfoProcSlice(name string, args ...int) ([]KinfoProc, error) {
mib, err := sysctlmib(name, args...)
if err != nil {
return nil, err
}

View File

@@ -267,3 +267,28 @@ func TestSysctlKinfoProc(t *testing.T) {
t.Errorf("got pid %d, want %d", got, want)
}
}
func TestSysctlKinfoProcSlice(t *testing.T) {
kps, err := unix.SysctlKinfoProcSlice("kern.proc.all")
if err != nil {
t.Fatalf("SysctlKinfoProc: %v", err)
}
if len(kps) == 0 {
t.Errorf("SysctlKinfoProcSlice: expected at least one process")
}
uid := unix.Getuid()
kps, err = unix.SysctlKinfoProcSlice("kern.proc.uid", uid)
if err != nil {
t.Fatalf("SysctlKinfoProc: %v", err)
}
if len(kps) == 0 {
t.Errorf("SysctlKinfoProcSlice: expected at least one process")
}
for _, kp := range kps {
if got, want := int(kp.Eproc.Ucred.Uid), uid; got != want {
t.Errorf("process %d: got uid %d, want %d", kp.Proc.P_pid, got, want)
}
}
}