Get the parent process id for a given pid

I was really surprised that there seems to be no posix or Cocoa API to get the parent process id on OS X when you already know a process id. This is expecially useful if you have started a process in form of an NSTask, but that task forks and so you cannot identify the process by -[NSTask processIdentifier] any more. This is now possible with the following small function by comparing the parent process id:


#include <sys/sysctl.h>

#define OPProcessValueUnknown UINT_MAX

int OPParentIDForProcessID(int pid)
/*" Returns the parent process id 
     for the given process id (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 OPProcessValueUnknown;
    if (length == 0)
        return OPProcessValueUnknown;
    return info.kp_eproc.e_ppid;
}

Have fun!

Dirk

Print this page  PDF version

2 Comments

On Jun 24, 2007, Keffer wrote:

Incredible.

Just a little message to congrats you for the incredible application Picnic, now if it's can work over internet, it will be magic :)

Cheers.


On Mar 4, 2008, Ameet wrote:

rthrth


Leave a comment...

Your Name

Your Web site URL (optional)

Your e-mail address (optional)

Title

Your comment here please:
Note: You can use Wiki markup to format your comment. No HTML please.