Finally found a way to programmatically do this without parsing the output of 'ps'
uint getUidUsingSysctl(uint pid) { struct kinfo_proc *sProcesses = NULL, *sNewProcesses; int aiNames[4]; size_t iNamesLength; int i, iRetCode, iNumProcs; size_t iSize; iSize = 0; aiNames[0] = CTL_KERN; aiNames[1] = KERN_PROC; aiNames[2] = KERN_PROC_ALL; aiNames[3] = 0; iNamesLength = 3; iRetCode = sysctl(aiNames, iNamesLength, NULL, &iSize, NULL, 0); do { iSize += iSize / 10; sNewProcesses = (kinfo_proc *)realloc(sProcesses, iSize); if (sNewProcesses == 0) { if (sProcesses) free(sProcesses); return -1; } sProcesses = sNewProcesses; iRetCode = sysctl(aiNames, iNamesLength, sProcesses, &iSize, NULL, 0); } while (iRetCode == -1 && errno == ENOMEM); iNumProcs = iSize / sizeof(struct kinfo_proc); for (i = 0; i < iNumProcs; i++) { if (sProcesses[i].kp_proc.p_pid == pid) { return sProcesses[i].kp_eproc.e_ucred.cr_uid; } } free(sProcesses); return -1; }
Note. Perhaps the best way to get "kinfo_proc" instead of repeating the whole process.
source share