How to programatically get uid from pid in osx using c++? How to programatically get uid from pid in osx using c++? unix unix

How to programatically get uid from pid in osx using c++?


Solution from Indhu helped me on my way, so I would like to post my own.

UID from PID with pure C:

#include <sys/sysctl.h>uid_t uidFromPid(pid_t pid){    uid_t uid = -1;    struct kinfo_proc process;    size_t procBufferSize = sizeof(process);    // Compose search path for sysctl. Here you can specify PID directly.    const u_int pathLenth = 4;    int path[pathLenth] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};    int sysctlResult = sysctl(path, pathLenth, &process, &procBufferSize, NULL, 0);    // If sysctl did not fail and process with PID available - take UID.    if ((sysctlResult == 0) && (procBufferSize != 0))    {        uid = process.kp_eproc.e_ucred.cr_uid;    }    return uid;}

No excess allocation, no loops.


The source for the ps command, reveals that there is a function called get_proc_stats defined in proc/readproc.h that (among other things) returns the real user name(UID) & Effective user name(EUID) for a given pid.

You need to do install libproc-dev to get this function. and then you can do:

#include <proc/readproc.h>void printppid(pid_t pid) {    proc_t process_info;    get_proc_stats(pid, &process_info);    printf("Real user of the process[%d] is [%s]\n", pid, process_info.ruser);}

compile it with gcc the-file.c -lproc.

Once you have the real user name you can use getpwnam() and getgrnam() functions to get the uid.


You could look at how ps does it. It looks like it uses the kvm_getprocs function.

However, it's much more portable (you said "any unix", but e.g. the Linux and Solaris way is to look in the /proc filesystem - and other unixes may have different APIs) to just parse the output of ps (ps -o user= -p (pid) for example, to eliminate any extraneous output) than to do any system-specific process stuff