func GetInfoForPid()

in metric/system/process/process_darwin.go [96:153]


func GetInfoForPid(_ resolve.Resolver, pid int) (ProcState, error) {
	info := C.struct_proc_taskallinfo{}

	size := C.int(unsafe.Sizeof(info))
	ptr := unsafe.Pointer(&info)

	// For docs, see the link below. Check the `proc_taskallinfo` struct, which
	// is a composition of `proc_bsdinfo` and `proc_taskinfo`.
	// https://opensource.apple.com/source/xnu/xnu-1504.3.12/bsd/sys/proc_info.h.auto.html
	n, err := C.proc_pidinfo(C.int(pid), C.PROC_PIDTASKALLINFO, 0, ptr, size)
	if n != size {
		return ProcState{}, fmt.Errorf("could not read process info for pid %d: proc_pidinfo returned %d, err: %w", pid, int(n), err)
	}

	status := ProcState{}

	status.Name = C.GoString(&info.pbsd.pbi_comm[0])

	switch info.pbsd.pbi_status {
	case C.SIDL:
		status.State = Idle
	case C.SRUN:
		status.State = Running
	case C.SSLEEP:
		status.State = Sleeping
	case C.SSTOP:
		status.State = Stopped
	case C.SZOMB:
		status.State = Zombie
	default:
		status.State = Unknown
	}

	status.Ppid = opt.IntWith(int(info.pbsd.pbi_ppid))
	status.Pid = opt.IntWith(pid)
	status.Pgid = opt.IntWith(int(info.pbsd.pbi_pgid))
	status.NumThreads = opt.IntWith(int(info.ptinfo.pti_threadnum))

	// Get process username. Fallback to UID if username is not available.
	uid := strconv.Itoa(int(info.pbsd.pbi_uid))
	user, err := user.LookupId(uid)
	if err == nil && user.Username != "" {
		status.Username = user.Username
	} else {
		status.Username = uid
	}

	// grab memory info + process time while we have it from struct_proc_taskallinfo
	status.Memory.Size = opt.UintWith(uint64(info.ptinfo.pti_virtual_size))
	status.Memory.Rss.Bytes = opt.UintWith(uint64(info.ptinfo.pti_resident_size))

	status.CPU.User.Ticks = opt.UintWith(uint64(info.ptinfo.pti_total_user) / uint64(time.Millisecond))
	status.CPU.System.Ticks = opt.UintWith(uint64(info.ptinfo.pti_total_system) / uint64(time.Millisecond))
	status.CPU.Total.Ticks = opt.UintWith(opt.SumOptUint(status.CPU.User.Ticks, status.CPU.System.Ticks))
	status.CPU.StartTime = unixTimeMsToTime((uint64(info.pbsd.pbi_start_tvsec) * 1000) + (uint64(info.pbsd.pbi_start_tvusec) / 1000))

	return status, nil
}