Posts Tagged ‘owner’

Getting the owner of a process

Thursday, December 6th, 2007

I was a little surprised that I couldn’t find this online anywhere, so for others that may need it, here’s a function that gets the effective owner of a Mac OS X process, given the process pid:

uid_t OwnerForPID(int pid)
{
    struct kinfo_proc info;
    size_t length = sizeof(struct kinfo_proc);
    int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, pid };
    if (sysctl(mib, 4, &info, &length, NULL, 0) < 0)
        return kProcessValueUnknown;
    if (length == 0)
        return kProcessValueUnknown;
    return info.kp_eproc.e_ucred.cr_uid;
}

And of course, you know you can get your own process ID with getpid() and use the Process Manager’s GetProcessPID() function to get a pid if you know another process’ ProcessSerialNumber.