Getting the owner of a process

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.

Tags: , , , , , ,

2 Responses to “Getting the owner of a process”

  1. G says:

    Thanks. I’m just starting to code for the first time. I love finding little gems like this. Please post more about the process of creating an app like DF.

  2. Jon says:

    Glad I could help G! Honestly, this little snippet really counts as “esoteric code.” There aren’t that many instances in Mac OS X programming where you actually need to know the owner of a process – I had to get it to know whether I should continue trying to send an AppleEvent to another process, or whether to just give up because I didn’t have permission to talk to that process in the first place.

    I’ll try and post some more after the “release rush” is done for DFX.

    – Jon

Leave a Reply